-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
576 lines (517 loc) · 15.3 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
const express = require('express');
const cors = require('cors');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
require('dotenv').config();
const jwt = require('jsonwebtoken');
require('colors');
const stripe = require("stripe")(process.env.STRIPE_SECRET);
const app = express();
const port = process.env.PORT || 4000;
//Middle wares
app.use(cors());
app.use(express.json());
// configure MongoDB
const uri = process.env.DB_URI;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
const usersCollection = client.db('computerBazar').collection('users');
const categoriesCollection = client.db('computerBazar').collection('productCategories');
const productsCollection = client.db('computerBazar').collection('products');
const bookingsCollection = client.db('computerBazar').collection('bookings');
const paymentsCollection = client.db('computerBazar').collection('payments');
// Verify JWT
function verifyJWT(req, res, next) {
const authHeader = req.headers.authorization;
// console.log({ authHeader });
if (!authHeader) {
return res.status(401).send('Unauthorized access');
}
const token = authHeader.split(' ')[1];
jwt.verify(token, process.env.ACCESS_TOKEN, function (err, decoded) {
if (err) {
return res.status(403).send({ message: 'Forbidden access' })
}
req.decoded = decoded;
next();
})
}
// CREATE verifyAdmin middleware
const verifyAdmin = async (req, res, next) => {
console.log('Inside verifyAdmin', req.decoded.email);
const decodedEmail = req.decoded.email;
console.log(decodedEmail);
const query = { email: decodedEmail };
const user = await usersCollection.findOne(query);
// console.log('user from 261', user);
if (user?.role !== 'admin') {
return res.status(403).send({ message: 'Forbidden access' })
}
next();
}
// Create verifySeller middleware
const verifySeller = async (req, res, next) => {
const decodedEmail = req.decoded.email;
const query = { email: decodedEmail };
const user = await usersCollection.findOne(query);
if (user?.role !== 'seller') {
return res.status(403).send({ message: 'Forbidden access' })
}
next();
}
// Create verifyBuyer middleware
const verifyBuyer = async (req, res, next) => {
const decodedEmail = req.decoded.email;
const query = { email: decodedEmail };
const user = await usersCollection.findOne(query);
if (user?.role !== 'buyer') {
return res.status(403).send({ message: 'Forbidden access' })
}
next();
}
async function run() {
try {
await client.connect();
console.log('Database Connected'.yellow);
} catch (error) {
console.log(error.name.bgRed, error.message.bold, error.stack);
}
}
run();
//JWT
app.get('/jwt', async (req, res) => {
const email = req.query.email;
const user = await usersCollection.findOne({ email: email });
if (user) {
var token = jwt.sign({ email }, process.env.ACCESS_TOKEN, { expiresIn: '10d' });
return res.send({ accessToken: token });
}
// console.log(user);
res.status(403).send({ accessToken: '' });
})
// find if admin or not
app.get('/user/admin/:email', async (req, res) => {
const email = req.params.email;
const query = { email };
const user = await usersCollection.findOne(query);
res.send({ isAdmin: user?.role === 'admin' });
})
// find if seller or not
app.get('/user/seller/:email', async (req, res) => {
const email = req.params.email;
const query = { email };
const user = await usersCollection.findOne(query);
res.send({
isSeller: user?.role === 'seller',
isSellerVerified: user?.isSellerVerified
});
})
// find if buyer or not
app.get('/user/buyer/:email', async (req, res) => {
const email = req.params.email;
const query = { email };
const user = await usersCollection.findOne(query);
res.send({ isBuyer: user?.role === 'buyer' });
})
// save users to db
app.post('/user', async (req, res) => {
try {
console.log(req.body);
const user = await usersCollection.insertOne(req.body);
console.log(user);
res.send({
status: true,
message: `The user successfully added`
})
} catch (error) {
console.log(error.name, error.message);
res.send({
status: false,
error: error
})
}
});
// Save user email when user login with Google email
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)
console.log(result)
res.send(result)
})
//get categories from db
app.get('/product-categories', async (req, res) => {
try {
const query = {}
const productCategories = await categoriesCollection.find(query).toArray();
res.send({
status: true,
productCategories
})
} catch (error) {
res.send({
status: false,
error: error
})
}
})
//Insert the product using post method
app.post('/add-product', verifyJWT, async (req, res) => {
try {
const product = await productsCollection.insertOne(req.body);
res.send({
status: true,
message: `You have successfully added ${req.body.title}!`
})
} catch (error) {
res.send({
status: false,
error: error.message
})
}
})
// get the products using category
app.get('/category/:id', async (req, res) => {
try {
const id = req.params.id;
// const query = { category_id: id }
const query = {
$and: [
{
category_id: id
},
{
$or: [
{ isSold: false },
{ isSold: { $exists: false } }
]
}
]
}
const categoryProducts = await productsCollection.find(query).toArray();
res.send({
status: true,
categoryProducts
})
} catch (error) {
res.send({
status: false,
error: error
})
}
})
app.post('/booking', async (req, res) => {
try {
const booking = await bookingsCollection.insertOne(req.body);
res.send({
status: true,
message: `You have successfully booked ${req.body.productName}!`
})
} catch (error) {
res.send({
status: false,
error: error.message
})
}
})
//get the advertised products and make sure the product is available
app.get('/advertised-products', verifyJWT, async (req, res) => {
try {
const query = {
$and: [
{
isAdvertised: true
},
{
$or: [
{ isSold: false },
{ isSold: { $exists: false } }
]
}
]
};
const adsProducts = await productsCollection.find(query).toArray();
res.send({
status: true,
adsProducts
})
} catch (error) {
res.send({
status: false,
error: error.message
})
}
})
//get the products for specific seller
app.get('/my-products', verifyJWT, verifySeller, async (req, res) => {
try {
const products = await productsCollection.find({ sellerEmail: req.query.email }).toArray();
res.send({
status: true,
products
})
} catch (error) {
console.log(error.name, error.message);
res.send({
status: false,
error: error.message
})
}
})
//update the product sales status from the my products //should be verifySeller
app.patch('/my-product/:id', verifyJWT, async (req, res) => {
try {
const id = req.params.id;
const status = req.body.status;
// console.log('inside', id, status);
const query = { _id: ObjectId(id) };
const updatedDoc = {
$set: {
isSold: status
}
}
const result = await productsCollection.updateOne(query, updatedDoc);
console.log(result);
res.send({
status: true,
message: `The product is marked as ${status ? 'Sold' : 'Available'}`
});
} catch (error) {
res.send({
status: false,
error: error.message
})
}
})
//make the product advertised/featured //should be verifySeller
app.patch('/my-product/ad/:id', verifyJWT, async (req, res) => {
try {
const id = req.params.id;
const status = req.body.status;
// console.log('inside ad', id, status);
const query = { _id: ObjectId(id) };
const updatedDoc = {
$set: {
isAdvertised: status
}
}
const result = await productsCollection.updateOne(query, updatedDoc);
res.send({
status: true,
message: `You have successfully boosted this product!}`
});
} catch (error) {
res.send({
status: false,
error: error.message
})
}
})
// delete the product from my-products route
app.delete('/my-product/:id', verifyJWT, async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const result = await productsCollection.deleteOne(query);
res.send({
status: true,
message: 'The product has been deleted'
});
})
//get all the sellers
app.get('/all-sellers', async (req, res) => {
try {
const query = { role: 'seller' };
const allSellers = await usersCollection.find(query).toArray();
res.send({
status: true,
allSellers
})
} catch (error) {
res.send({
status: false,
error: error.message
})
}
})
//make the seller verified //should be verifyAdmin
app.patch('/seller/:id', verifyJWT, async (req, res) => {
try {
const id = req.params.id;
const status = req.body.status;
console.log('inside', id, status);
const query = { _id: ObjectId(id) };
const updatedDoc = {
$set: {
isSellerVerified: status
}
}
const result = await usersCollection.updateOne(query, updatedDoc);
const productResult = await productsCollection.updateOne(query, updatedDoc);
res.send({
status: true,
message: `You have successfully verified the seller!`
});
} catch (error) {
res.send({
status: false,
error: error.message
})
}
})
// delete the seller from all-seller route //verifyAdmin
app.delete('/seller/:id', verifyJWT, async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const result = await usersCollection.deleteOne(query);
res.send({
status: true,
message: 'The Seller has been deleted!'
});
})
//get all the buyers
app.get('/all-buyers', async (req, res) => {
try {
const query = { role: 'buyer' };
const allBuyers = await usersCollection.find(query).toArray();
res.send({
status: true,
allBuyers
})
} catch (error) {
res.send({
status: false,
error: error.message
})
}
})
// delete the buyers from all-buyers route //verifyAdmin
app.delete('/buyer/:id', verifyJWT, async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const result = await usersCollection.deleteOne(query);
res.send({
status: true,
message: 'The Buyer has been deleted!'
});
})
//make the product reported //should be verifyBuyer
app.patch('/reported-product/:id', verifyJWT, async (req, res) => {
try {
const id = req.params.id;
const status = req.body.status;
const query = { _id: ObjectId(id) };
const updatedDoc = {
$set: {
isReported: status
}
}
const result = await productsCollection.updateOne(query, updatedDoc);
res.send({
status: true,
message: `You have successfully reported this product. We'll verify the product soon!`
});
} catch (error) {
res.send({
status: false,
error: error.message
})
}
})
//get the reported products
app.get('/reported-products', verifyJWT, async (req, res) => {
try {
const reportedProducts = await productsCollection.find({ isReported: true }).toArray();
res.send({
status: true,
reportedProducts
})
} catch (error) {
res.send({
status: false,
error: error.message
})
}
})
// get the orders/booking info for specific buyers
app.get('/my-orders', verifyJWT, verifyBuyer, async (req, res) => {
try {
const myOrders = await bookingsCollection.find({ email: req.query.email }).toArray();
res.send({
status: true,
myOrders
})
} catch (error) {
res.send({
status: false,
error: error.message
})
}
})
//find booking/order to payment
app.get('/order/:id', async (req, res) => {
try {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const order = await bookingsCollection.findOne(query);
res.send({
status: true,
order
})
} catch (error) {
res.send({
status: false,
error: error.message
})
}
})
// payment gateway integration
app.post("/create-payment-intent", async (req, res) => {
const order = req.body;
const price = order.price;
const amount = price * 100;
// Create a PaymentIntent with the order amount and currency
const paymentIntent = await stripe.paymentIntents.create({
amount: amount,
currency: "bdt",
payment_method_types: [
"card"
]
});
res.send({
clientSecret: paymentIntent.client_secret,
});
});
// save payments to db
app.post('/payment', async (req, res) => {
try {
const payment = req.body;
const result = await paymentsCollection.insertOne(payment);
const id = payment.bookingId;
const filter = { _id: ObjectId(id) };
const updatedDoc = {
$set: {
paid: true,
transactionId: payment.transactionId
}
}
const updatedResult = await bookingsCollection.updateOne(filter, updatedDoc);
res.send({
status: true,
message: "The payment has been completed!"
})
} catch (error) {
res.send({
status: false,
error: error.message
})
}
})
app.get('/', (req, res) => {
res.send("Computer Bazar Server is Running");
})
app.listen(port, () => {
console.log(`Computer Bazar is running on port ${port}`.cyan.bold);
})