-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
709 lines (625 loc) · 21.7 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
const express = require("express");
const { MongoClient, ServerApiVersion, ObjectId } = require("mongodb");
require("dotenv").config();
const app = express();
const moment = require("moment");
const cors = require("cors");
app.use(cors());
var jwt = require("jsonwebtoken");
app.use(express.json());
const nodemailer = require("nodemailer");
const port = process.env.PORT || 4000;
// username: digi_money1
// password: 0cmJopaqLVn7snJi
const uri =
"mongodb+srv://digi_money1:0cmJopaqLVn7snJi@cluster0.928uo.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverApi: ServerApiVersion.v1,
});
// ============================================== Sending to receiver email ==============================================
function receiverMail(addTransectionToReceiver) {
const {
senderEmail,
senderAccountNumber,
receive_money,
data,
reciverEmail,
} = addTransectionToReceiver.$push.transection;
// sending mail via nodemailer
const msg = {
from: "testingdeveloper431@gmail.com", // sender address
to: ` ${reciverEmail}`, // list of receivers
subject: `Money Recived from ${senderEmail}`, // Subject line
text: "hey you got a info", // plain text body
html: `
<p>Hey</p></br>
<p>Your account has recived ${receive_money}$ from Account Number ${senderAccountNumber}
</p> </br>
<p>Best Regards</p> </br>
<p>Digi Money Bank</p>
`,
};
nodemailer
.createTransport({
service: "gmail",
auth: {
user: "testingdeveloper431@gmail.com",
pass: "ajexwpkgpewiohct",
},
port: 587,
host: "smtp.ethereal.email",
})
.sendMail(msg, (err) => {
if (err) {
return console.log("Error occures", err);
} else {
return console.log("email sent");
}
});
}
//======================================== jot web token authorization for all users ===================================
function verifyJWT(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).send({ message: "UnAuthorized access" });
}
const token = authHeader.split(" ")[1];
jwt.verify(token, process.env.SECRET_KEY, function (err, decoded) {
if (err) {
return res.status(403).send({ message: "Forbidden access" });
}
req.decoded = decoded;
next();
});
}
// ============================================== Sending to sender email ==============================================
function senderMail(addTransection) {
const { senderEmail, receiverAccountnumber, amount, data, reciverEmail } =
addTransection.$push.transection;
// sending mail via nodemailer
//
const msg = {
from: "testingdeveloper431@gmail.com", // sender address
to: `${senderEmail}`, // list of receivers
subject: `Money sent to from ${reciverEmail}`, // Subject line
text: "hey you got a info", // plain text body
html: `
<p>Hey</p></br>
<p>Your account has send ${amount}$ to Account Number ${receiverAccountnumber}
</p> </br>
<p>Best Regards</p> </br>
<p>Digi Money Bank</p>
`,
};
nodemailer
.createTransport({
service: "gmail",
auth: {
user: "testingdeveloper431@gmail.com",
pass: "ajexwpkgpewiohct",
},
port: 587,
host: "smtp.ethereal.email",
})
.sendMail(msg, (err) => {
if (err) {
return console.log("Error occures", err);
} else {
return console.log("email sent");
}
});
}
async function run() {
try {
await client.connect();
const usersCollection = client.db("digi_money1").collection("users");
const approvedUsersCollection = client
.db("digi_money1")
.collection("approvedUsers");
const usersReviewCollection = client
.db("digi_money1")
.collection("reviews");
const transectionCollection = client
.db("digi_money1")
.collection("transection");
const tokenUserCollection = client.db("digi_money1").collection("user");
const blogCollection = client.db("digi_money1").collection("blog");
const randomVisitorCollection = client
.db("digi_money1")
.collection("randomvisitor");
const subscribeCollection = client
.db("digi_money1")
.collection("subscribe");
const bankDataCollection = client.db("digi_money1").collection("bankdata");
//userCollection for generate web token
app.put("/user/:email", async (req, res) => {
const email = req.params.email;
const user = req.body;
const filter = { email: email };
const options = { upsert: true };
const updateDoc = {
$set: user,
};
const token = jwt.sign({ email: email }, process.env.SECRET_KEY, {
expiresIn: "7d",
});
const result = await tokenUserCollection.updateOne(
filter,
updateDoc,
options
);
res.send({ token });
});
// create new user and save the user data to database
app.post("/adduser", async (req, res) => {
const user = req.body;
const result = await usersCollection.insertOne(user);
res.send(result);
});
app.get("/users", async (req, res) => {
const query = {};
const cursor = usersCollection.find(query);
const users = await cursor.toArray();
res.send(users);
});
// delete from users a user
app.delete("/users/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const result = await usersCollection.deleteOne(query);
res.send(result);
});
//=======================================================check approved user============================================//
app.get("/checkuser:email", async (req, res) => {
const email = req.params.email;
const result = await approvedUsersCollection.findOne({ email: email });
if (result) {
res.send({ userexist: true });
return;
} else {
res.send({ userexist: false });
return;
}
});
app.get("/approvedUsers", async (req, res) => {
const query = {};
const cursor = approvedUsersCollection.find(query);
const users = await cursor.toArray();
res.send(users);
});
app.get("/finduser", verifyJWT, async (req, res) => {
const email = req.query.email;
const result = await approvedUsersCollection.findOne({ email: email });
if (!result) {
res.send({ find: false });
return;
} else {
res.send(result);
}
});
// adding account number
app.patch("/accountNumber/:id", async (req, res) => {
const id = req.params.id;
const data = req.body;
const query = { _id: ObjectId(id) };
const update = {
$set: {
accountNumber: data.accountNumber,
},
};
const result = await usersCollection.updateOne(query, update);
res.send(result);
});
// post approved users
app.post("/approvedUsers", async (req, res) => {
const newUser = req.body;
const result = await approvedUsersCollection.insertOne(newUser);
res.send(result);
});
//============================================ update ammount===========================================//
app.patch("/approvedUsers/:id", async (req, res) => {
const id = req.params.id;
const updatedAmount = req.body;
const bankInfo = await bankDataCollection.findOne({
_id: ObjectId("630f439efda2555ca01f5ea0"),
});
const updatedBankAmount = bankInfo.amount - updatedAmount.withdrawAmount;
const updateBank = {
$set: { amount: updatedBankAmount },
};
const ifUpdated = await bankDataCollection.updateOne(
{ _id: ObjectId("630f439efda2555ca01f5ea0") },
updateBank
);
const query = { accountNumber: id };
const update = {
$set: {
amount: updatedAmount.amount,
},
};
const result = await approvedUsersCollection.updateOne(query, update);
res.send(result);
});
// ==========================================deposite amount=========================================//
app.patch("/deposite/:accountnumber", async (req, res) => {
const accountNumber = req.params.accountnumber;
const updatedAmount = req.body;
const bankInfo = await bankDataCollection.findOne({
_id: ObjectId("630f439efda2555ca01f5ea0"),
});
const updatedBankAmount = bankInfo.amount + updatedAmount.depositeAmount;
const updateBank = {
$set: { amount: updatedBankAmount },
};
const ifUpdated = await bankDataCollection.updateOne(
{ _id: ObjectId("630f439efda2555ca01f5ea0") },
updateBank
);
const query = { accountNumber: accountNumber };
const update = {
$set: {
amount: updatedAmount.amount,
},
};
const result = await approvedUsersCollection.updateOne(query, update);
res.send(result);
});
app.put("/approvedUsers/admin/:email", async (req, res) => {
const email = req.params.email;
const filter = { email: email };
const updateDoc = {
$set: { role: "admin" },
};
const result = await approvedUsersCollection.updateOne(filter, updateDoc);
res.send(result);
});
app.get("/approvedUser/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: id };
const user = await approvedUsersCollection.findOne(query);
res.send(user);
});
app.put("/user/:email", async (req, res) => {
const email = req.params.email;
const user = req.body;
const filter = { email: email };
const options = { upsert: true };
const updateDoc = {
$set: user,
};
const result = await usersCollection.updateOne(
filter,
updateDoc,
options
);
res.send({ result });
});
// ===========================================================profile picture update============================================//
app.patch("/profile/:email",async(req,res)=>{
const email=req.params.email;
const profilePicture=req.body;
const filter={email:email}
const update={
$set:{
profileImage:profilePicture.profileImg
}
}
const result=await approvedUsersCollection.updateOne(filter,update)
res.send(result)
})
// delete from users a user
app.delete("/users/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const result = await usersCollection.deleteOne(query);
res.send(result);
});
app.get("/approvedUsers", async (req, res) => {
const query = {};
const cursor = approvedUsersCollection.find(query);
const users = await cursor.toArray();
res.send(users);
});
// adding account number
app.patch("/accountNumber/:id", async (req, res) => {
const id = req.params.id;
const data = req.body;
const query = { _id: ObjectId(id) };
const update = {
$set: {
accountNumber: data.accountNumber,
},
};
const result = await usersCollection.updateOne(query, update);
res.send(result);
});
// post approved users
app.post("/approvedUsers", async (req, res) => {
const newUser = req.body;
const result = await approvedUsersCollection.insertOne(newUser);
res.send(result);
});
app.put("/approvedUsers/admin/:email", async (req, res) => {
const email = req.params.email;
const filter = { email: email };
const updateDoc = {
$set: { role: "admin" },
};
const result = await approvedUsersCollection.updateOne(filter, updateDoc);
res.send(result);
});
app.get("/approvedUser/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: id };
const user = await approvedUsersCollection.findOne(query);
res.send(user);
});
app.put("/user/:email", async (req, res) => {
const email = req.params.email;
const user = req.body;
const filter = { email: email };
const options = { upsert: true };
const updateDoc = {
$set: user,
};
const result = await usersCollection.updateOne(
filter,
updateDoc,
options
);
res.send({ result });
});
// delete from users a user
app.delete("/users/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const result = await usersCollection.deleteOne(query);
res.send(result);
});
// post approved users
app.post("/approvedUsers", async (req, res) => {
const newUser = req.body;
const result = await approvedUsersCollection.insertOne(newUser);
res.send(result);
});
// Get a single user information
app.get("/approvedUsers", async (req, res) => {
const query = {};
const cursor = approvedUsersCollection.find(query);
const users = await cursor.toArray();
res.send(users);
});
// post approved users
app.post("/approvedUser", async (req, res) => {
const newUser = req.body;
const result = await approvedUsersCollection.insertOne(newUser);
res.send(result);
});
app.delete("/approvedUser/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: id };
const result = await approvedUsersCollection.deleteOne(query);
res.send(result);
});
app.put("/approvedUser/admin/:email", async (req, res) => {
const email = req.params.email;
const filter = { email: email };
const updateDoc = {
$set: { role: "admin" },
};
const result = await approvedUsersCollection.updateOne(filter, updateDoc);
res.send(result);
});
app.get("/approvedUser/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: id };
const user = await approvedUsersCollection.findOne(query);
res.send(user);
});
// ===============================================customer review ============================================//
// Insert review data to database
app.post("/review", async (req, res) => {
const review = req.body;
const result = await usersReviewCollection.insertOne(review);
res.send(result);
});
//get all review data from database
app.get("/review", async (req, res) => {
const result = await usersReviewCollection.find({}).toArray();
res.send(result);
});
// ==================================================Check admin ============================================//
app.get("/admin", async (req, res) => {
const email = req.query.email;
const getUser = await approvedUsersCollection.findOne({ email: email });
if (getUser) {
const isAdmin = getUser.role === "admin";
return res.send({ admin: isAdmin });
} else {
return res.send({ admin: false });
}
});
// ==============================================Transfer Balance==========================================//
app.patch("/transfer", async (req, res) => {
const { accountNumber, amount } = req.body;
const email = req.query.email;
const receiverinfoquery = { accountNumber: accountNumber };
const senderinfoquery = { email: email };
// find receiver account by account number
const findTargetedaccount = await approvedUsersCollection.findOne(
receiverinfoquery
);
if (!findTargetedaccount) {
return res.send({ message: "Account number did not match " });
}
const updateAmount =
parseFloat(findTargetedaccount.amount) + parseFloat(amount);
const update = {
$set: {
amount: updateAmount,
},
};
const transferBalance = await approvedUsersCollection.updateOne(
receiverinfoquery,
update
);
if (transferBalance.modifiedCount) {
const findSenderInfo = await approvedUsersCollection.findOne(
senderinfoquery
);
const updateSenderAmount =
parseFloat(findSenderInfo.amount) - parseFloat(amount);
const updatesender = {
$set: {
amount: updateSenderAmount,
},
};
const finalResult = await approvedUsersCollection.updateOne(
senderinfoquery,
updatesender
);
// add transection to sender database
const addTransection = {
$push: {
["transection"]: {
send_money: amount,
receiverAccountnumber: accountNumber,
senderEmail: findSenderInfo.email,
reciverEmail: findTargetedaccount.email,
staus: "complete",
statustwo: "outgoing",
data: new Date(),
reveiverName: findTargetedaccount.displayName,
},
},
};
senderMail(addTransection);
const insertTransection = await approvedUsersCollection.updateOne(
senderinfoquery,
addTransection
);
//add transection object to receiver database
const addTransectionToReceiver = {
$push: {
["transection"]: {
receive_money: amount,
senderAccountNumber: findSenderInfo.accountNumber,
senderEmail: findSenderInfo.email,
reciverEmail: findTargetedaccount.email,
staus: "complete",
statustwo: "incomming",
data: new Date(),
senderName: findSenderInfo.displayName,
},
},
};
receiverMail(addTransectionToReceiver);
const insertTransectionDataToReceiver =
await approvedUsersCollection.updateOne(
receiverinfoquery,
addTransectionToReceiver
);
res.send({
finalResult,
insertTransectionDataToReceiver,
insertTransection,
});
}
});
// pagenation for transection history
app.get("/transectionCount/:account", async (req, res) => {
const accountNumber = req.params.account;
const findDocument = await approvedUsersCollection.findOne({
accountNumber: accountNumber,
});
const transectionHistory = findDocument?.transection;
const count = transectionHistory?.length;
if (count) {
res.send({ count });
}
});
// get all transection
app.get("/transection/:account", verifyJWT, async (req, res) => {
const page = req.query.page;
const accountNumber = req.params.account;
const findDocument = await approvedUsersCollection.findOne({
accountNumber: accountNumber,
});
const transectionHistory = findDocument?.transection;
let sortedTransection = [];
if (transectionHistory) {
let sorted = [...transectionHistory].sort(
(a, b) =>
new moment(a.date).format("YYYYMMDD") -
new moment(b.date).format("YYYYMMDD")
);
sortedTransection = sorted.reverse();
}
if (page == 0) {
res.send(sortedTransection);
return;
}
function paginateArray(arr, itemPerPage, pageIndex) {
const lastIndex = itemPerPage * pageIndex;
const firstIndex = lastIndex - itemPerPage;
return arr.slice(firstIndex, lastIndex);
}
const index = parseInt(page);
const result = paginateArray(sortedTransection, 10, index);
res.send(result);
});
// =============================================================load all blogs========================================//
app.get("/blog", async (req, res) => {
const result = await blogCollection.find({}).toArray();
res.send(result);
});
// ==============================================================find transection by account Number=======================//
app.get("/findtransection:accountNumber", async (req, res) => {
const accountNumber = req.params.accountNumber;
const query = { accountNumber: accountNumber };
const result = await approvedUsersCollection.findOne(query);
const transection = result.transection.reverse();
res.send(transection);
});
// =============================================================guest data collection //bottaom banner form ==================================//
app.post("/visitordata", async (req, res) => {
const visitordata = req.body;
const { email } = visitordata;
const isMatch = await randomVisitorCollection.findOne({ email: email });
if (isMatch) {
res.send({ message: "email already exist " });
return;
} else {
const result = await randomVisitorCollection.insertOne(visitordata);
res.send(result);
}
});
app.post("/subscribe", async (req, res) => {
const subscribeData = req.body;
const { email } = subscribeData;
const isMatch = await subscribeCollection.findOne({ email: email });
if (isMatch) {
res.send({ message: "Already subscribed " });
return;
} else {
const result = await subscribeCollection.insertOne(subscribeData);
res.send(result);
}
});
// ================================================our bank info============================
app.get("/bankinfo", async (req, res) => {
const result = await bankDataCollection.findOne({
_id: ObjectId("630f439efda2555ca01f5ea0"),
});
res.send(result);
});
} finally {
}
}
run().catch(console.dir);
app.get("/", (req, res) => {
res.send("digimoney server start successfully");
});
app.listen(port, () => console.log("Run successfully"));