-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
557 lines (520 loc) · 17.4 KB
/
app.js
File metadata and controls
557 lines (520 loc) · 17.4 KB
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
require('dotenv').config();
const express = require('express')
const app = express()
const PORT = process.env.port || 3000;
const path = require('path')
const hbs = require('hbs')
const fetch = require('node-fetch')
const jwt = require('jsonwebtoken')
const cookieParser = require('cookie-parser')
const { v4: uuidv4 } = require('uuid')
const Sib = require('sib-api-v3-sdk');
const multer = require('multer');
const validator = require('validator')
app.use(express.static('public'))
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(cookieParser())
app.use((req, res, next) => {
res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
res.header('Pragma', 'no-cache');
res.header('Expires', '-1');
next();
});
app.set('view engine', 'hbs');
app.set('views', './templates/views');
hbs.registerPartials(path.join(__dirname, 'templates/partials'));
const con = require('./src/db.js')
const otp = require('./src/otp.js')
const Data = require('./models/data.js')
const bcrypt = require('bcryptjs');
const auth = require('./middleware/auth.js');
const storage = require('./middleware/storage.js');
const upload = multer({ storage })
const defaultClient = Sib.ApiClient.instance;
const apiKey = defaultClient.authentications['api-key'];
apiKey.apiKey = process.env.BLUE_KEY;
const tranEmailApi = new Sib.TransactionalEmailsApi()
app.get('/', auth, async (req, res) => {
const id = req.id
const tmp = await Data.findOne({ _id: id });
let user = tmp.name.split(" ", 1);
user = String(user).charAt(0).toUpperCase() + String(user).slice(1);
res.render("home.hbs", {
iname: 'Hi, ' + user
})
})
app.get('/shop', auth, async (req, res) => {
//console.log(req.query.cat);
const id = req.id
const tmp = await Data.findOne({ _id: id });
let user = tmp.name.split(" ", 1);
user = String(user).charAt(0).toUpperCase() + String(user).slice(1);
if (req.query.cat) res.render("uCategory.hbs", {
shop: req.query.cat,
iname: 'Hi, ' + user
})
else res.render("uShop.hbs", {
iname: 'Hi, ' + user
})
})
app.get('/product', auth, async (req, res) => {
const id = req.id
const tmp = await Data.findOne({ _id: id });
let user = tmp.name.split(" ", 1);
let check = 0, fav = 0;
const li = tmp.cart, flist = tmp.favourites;
for (let i = 0; i < li.length; i++) if (li[i] === req.query.id) check = 1;
for (let i = 0; i < flist.length; i++) if (flist[i] === req.query.id) fav = 1;
user = String(user).charAt(0).toUpperCase() + String(user).slice(1);
if (req.query.id && req.query.cat) {
res.render("uProduct.hbs", {
iname: 'Hi, ' + user,
id: req.query.id,
cat: req.query.cat,
check: check,
fav: fav,
image: (tmp.image) ? tmp.image.slice(7) : 'https://mdbcdn.b-cdn.net/img/Photos/new-templates/bootstrap-chat/ava3.webp'
})
}
else if (req.query.uid) {
const user = await Data.findOne({ _id: req.query.uid });
res.send({
image: (user.image) ? user.image.slice(7) : 'https://mdbcdn.b-cdn.net/img/Photos/new-templates/bootstrap-chat/ava3.webp',
name: user.name
})
}
else res.sendFile(__dirname + '/src/error.html')
})
app.get('/user', auth, async (req, res) => {
const id = req.id
const tmp = await Data.findOne({ _id: id });
let user = tmp.name.split(" ", 1);
const full = tmp.name.split(" ");
let name = '';
for (let i = 0; i < full.length; i++) name += (full[i].charAt(0).toUpperCase() + full[i].slice(1) + ' ');
// name = name.slice(0, name.length - 1);
user = String(user).charAt(0).toUpperCase() + String(user).slice(1);
res.render("profile.hbs", {
iname: 'Hi, ' + user,
name: name,
email: tmp.email,
mobile: (tmp.mobile) ? tmp.mobile : 'Add Mobile No.',
address: (tmp.address) ? tmp.address : 'Add Address',
image: (tmp.image) ? tmp.image.slice(7) : 'https://mdbcdn.b-cdn.net/img/Photos/new-templates/bootstrap-chat/ava3.webp'
})
})
app.post('/user', auth, async (req, res) => {
const id = req.id
if (!validator.isEmail(req.body.email)) return res.send(false)
try {
const tmp = await Data.findOneAndUpdate({ _id: id }, {
$set: {
name: req.body.name,
email: req.body.email,
mobile: req.body.mobile,
address: req.body.address
}
})
console.log(tmp);
res.send(true);
} catch (error) {
res.sendStatus(502);
}
})
app.post('/upload', auth, upload.single('image'), async (req, res) => {
const id = req.id
console.log(req.body);
console.log(req.file);
try {
const tmp = await Data.findOneAndUpdate({ _id: id }, {
$set: {
image: req.file.path
}
})
// console.log(tmp);
res.redirect('/user');
} catch (error) {
res.sendStatus(502);
}
})
app.get('/search', auth, async (req, res) => {
const id = req.id
const tmp = await Data.findOne({ _id: id });
let user = tmp.name.split(" ", 1);
user = String(user).charAt(0).toUpperCase() + String(user).slice(1);
if (req.query.s) {
res.render("uSearch.hbs", {
iname: 'Hi, ' + user,
query: req.query.s
})
}
else res.sendFile(__dirname + '/src/error.html')
})
app.get('/pay', auth, async (req, res) => {
const id = req.id
const tmp = await Data.findOne({ _id: id });
let user = tmp.name.split(" ", 1);
user = String(user).charAt(0).toUpperCase() + String(user).slice(1);
if (req.query.order) {
const li = tmp.cart;
await Data.updateOne({ _id: id }, {
$set: {
cart: [],
orders: tmp.cart
}
})
res.render("confirm.hbs",)
}
else res.render("checkout.hbs", {
iname: 'Hi, ' + user,
id: id
})
})
app.get('/wishlist', auth, async (req, res) => {
const id = req.id
const tmp = await Data.findOne({ _id: id }).select({
name: 1,
favourites: 1
});
if (req.query.id) res.send(tmp)
else {
let user = tmp.name.split(" ", 1);
user = String(user).charAt(0).toUpperCase() + String(user).slice(1);
res.render("wishlist.hbs", {
iname: 'Hi, ' + user,
id: id
})
}
})
app.get('/orders', auth, async (req, res) => {
const id = req.id
const tmp = await Data.findOne({ _id: id }).select({
name: 1,
orders: 1
});
if (req.query.id) res.send(tmp)
else {
let user = tmp.name.split(" ", 1);
user = String(user).charAt(0).toUpperCase() + String(user).slice(1);
res.render("orders.hbs", {
iname: 'Hi, ' + user,
id: id
})
}
})
app.post('/wishlist', auth, async (req, res) => {
try {
await Data.updateOne({ _id: req.id }, {
$push: { favourites: req.body.id }
})
res.send(true)
} catch (error) {
res.send(false)
}
})
app.delete('/wishlist', auth, async (req, res) => {
try {
await Data.updateOne({ _id: req.id }, {
$pull: { favourites: req.body.id }
})
res.send(true)
} catch (error) {
res.send(false)
}
})
app.get('/cart', auth, async (req, res) => {
const id = req.id
const tmp = await Data.findOne({ _id: id }).select({
name: 1,
cart: 1
});
if (req.query.id) res.send(tmp)
else {
let user = tmp.name.split(" ", 1);
user = String(user).charAt(0).toUpperCase() + String(user).slice(1);
res.render("cart.hbs", {
iname: 'Hi, ' + user,
id: id
})
}
})
app.post('/cart', auth, async (req, res) => {
try {
await Data.updateOne({ _id: req.id }, {
$push: { cart: req.body.id }
})
res.send(true)
} catch (error) {
res.send(false)
}
})
app.delete('/cart', auth, async (req, res) => {
try {
await Data.updateOne({ _id: req.id }, {
$pull: { cart: req.body.id }
})
res.send(true)
} catch (error) {
res.send(false)
}
})
app.get('/about', auth, async (req, res) => {
const id = req.id
const tmp = await Data.findOne({ _id: id });
let user = tmp.name.split(" ", 1);
user = String(user).charAt(0).toUpperCase() + String(user).slice(1);
res.render("about.hbs", {
iname: 'Hi, ' + user
})
})
app.get('/login', (req, res) => {
if (req.cookies.jwt) res.redirect('/');
else res.sendFile(__dirname + '/src/login.html')
})
app.post('/login', async (req, res) => {
//console.log(req.body);
try {
const tmp = await Data.findOne({ email: req.body.email })
if (!tmp) res.status(400).render('bad.hbs', {
message: 'email id does not exists'
})
else if (!(await bcrypt.compare(req.body.password, tmp.password))) res.status(400).render('bad.hbs', {
message: 'password is incorrect'
})
else {
const id = tmp._id.valueOf();
//console.log(id.valueOf()); // get _id as a string from ObjectId
//console.log(id);
const uuid = uuidv4();
console.log(uuid);
const obj = {
_id: id,
rid: uuid
}
const token = jwt.sign(obj, process.env.SECRET_KEY)
res.cookie('jwt', token, {
expires: new Date(Date.now() + 86400000), // must add secure at production time
httpOnly: true
})
await Data.updateOne({ _id: id }, {
$push: { tokens: uuid }
})
res.redirect('/')
}
} catch (error) {
res.sendStatus(500)
}
})
app.get('/logout', auth, async (req, res) => {
res.clearCookie("jwt")
try {
const tmp = await Data.findOneAndUpdate({ _id: req.id }, {
$pull: { tokens: req.rid }
})
res.redirect('/')
} catch (error) {
res.sendStatus(500)
}
})
app.get('/register', async (req, res) => {
if (req.cookies.jwt) res.redirect('/');
else res.sendFile(__dirname + '/src/register.html')
})
app.post('/register', async (req, res) => {
try {
let tmp = await Data.findOne({ email: req.body.email })
if (tmp) res.redirect('/login')
else {
req.body.password = await bcrypt.hash(req.body.password, 10)
tmp = await Data.create(req.body)
console.log(tmp);
res.redirect('/')
}
} catch (error) {
res.sendStatus(502)
}
})
app.get('/forget', async (req, res) => {
if (req.cookies.jwt) res.redirect('/');
else res.sendFile(__dirname + '/src/email_verify.html')
})
app.post('/forget', async (req, res) => {
try {
const tmp = await Data.findOne({ email: req.body.email })
if (!tmp) res.redirect('/register')
else {
const sender = {
email: 'indimart@gmail.com',
name: 'indiMart'
}
const receivers = [{ email: req.body.email }]
const code = otp()
const token = jwt.sign({
otp: code,
email: req.body.email
}, process.env.SECRET_KEY)
res.cookie('code', token, {
expires: new Date(Date.now() + 300000),
httpOnly: true
})
tranEmailApi.sendTransacEmail({
sender,
to: receivers,
subject: 'Regarding email verification',
htmlContent: `Dear Customer,
Your OTP for email verification given below
<h1>${code}</h1>
Best regards,
<b>indiMart</b>`
})
.then(console.log)
.catch(console.log)
if (req.body.active) res.send({})
else res.render('verify_mail_send.hbs', {
email: req.body.email
})
}
} catch (error) {
res.sendStatus(502)
}
})
app.post('/verify', async (req, res) => {
try {
const token = req.cookies.code
const obj = jwt.verify(token, process.env.SECRET_KEY)
if (req.body.otp == obj.otp) {
res.send({
code: true
})
}
else res.send({
code: false
})
} catch (error) {
res.redirect('/login')
}
})
app.get('/password', (req, res) => {
try {
const token = req.cookies.code
const obj = jwt.verify(token, process.env.SECRET_KEY)
res.sendFile(__dirname + '/src/change_password.html')
} catch (error) {
res.redirect('/login')
}
})
app.patch('/password', async (req, res) => {
try {
const token = req.cookies.code
const obj = jwt.verify(token, process.env.SECRET_KEY)
req.body.password = await bcrypt.hash(req.body.password, 10)
try {
const tmp = await Data.findOneAndUpdate({ email: obj.email }, {
$set: {
password: req.body.password
}
})
console.log(tmp);
res.send(tmp)
} catch (error) {
res.sendStatus(502)
}
} catch (error) {
res.redirect('/login')
}
})
app.get('/terms', auth, async (req, res) => {
const id = req.id
const tmp = await Data.findOne({ _id: id });
let user = tmp.name.split(" ", 1);
user = String(user).charAt(0).toUpperCase() + String(user).slice(1);
res.render("terms.hbs", {
iname: 'Hi, ' + user
})
})
app.post('/review', auth, async (req, res) => {
//console.log(req.body);
const options = {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
pid: req.body.pid,
id: req.id,
review: req.body.review,
stars: Number(req.body.star)
})
};
let tmp = await fetch('https://martdb.onrender.com/review', options)
tmp = await tmp.json()
//console.log(tmp);
res.redirect(`/product?cat=${req.body.category}&id=${req.body.pid}`);
})
app.post('/contact', async (req, res) => {
if (!validator.isEmail(req.body.email)) return res.status.sendFile(__dirname + '/src/error.html')
let sender = {
email: req.body.email,
name: req.body.name
}
const receivers = [{ email: 'sundeep5521@gmail.com' }]
tranEmailApi.sendTransacEmail({
sender,
to: receivers,
subject: 'Feedback Request',
htmlContent: `${req.body.text}`
})
.then(console.log)
.catch(console.log)
sender = {
email: 'indimart@gmail.com',
name: 'indiMart'
}
tranEmailApi.sendTransacEmail({
sender,
to: [{ email: req.body.email }],
subject: 'Thank You for Your Valuable Feedback!',
htmlContent: `<div class="markdown prose w-full break-words dark:prose-invert light"><p>Dear ${req.body.name},</p><p>Thank you for choosing Indimart as your preferred destination for online shopping. We greatly appreciate your recent feedback and would like to express our gratitude for taking the time to share your thoughts with us.</p><p>Your feedback is vital to our continuous efforts in improving our website and enhancing the overall shopping experience for our valued customers like yourself. We understand that providing a seamless and enjoyable online shopping experience is crucial, and your input allows us to identify areas where we can further optimize our services.</p><p>Rest assured that your feedback has been noted, and our team will thoroughly review and analyze it. We take every comment seriously and consider each suggestion as an opportunity for growth and improvement.</p><p>We truly value your contribution as it helps us shape the future of Indimart. If you have any further feedback or suggestions, please feel free to reach out to us. We are here to listen and ensure that your voice is heard.</p><p>Once again, thank you for your valuable feedback. We look forward to serving you better and providing you with an exceptional shopping experience at Indimart.</p><p>Best regards,<br>
Sandeep<br>
Indimart Customer Support Team</p></div>`
}).then(console.log)
.catch(console.log)
res.redirect('/')
})
app.get('/privacy', auth, async (req, res) => {
const id = req.id
const tmp = await Data.findOne({ _id: id });
let user = tmp.name.split(" ", 1);
user = String(user).charAt(0).toUpperCase() + String(user).slice(1);
res.render("privacy.hbs", {
iname: 'Hi, ' + user
})
})
app.get('/refund', auth, async (req, res) => {
const id = req.id
const tmp = await Data.findOne({ _id: id });
let user = tmp.name.split(" ", 1);
user = String(user).charAt(0).toUpperCase() + String(user).slice(1);
res.render("refund.hbs", {
iname: 'Hi, ' + user
})
})
app.get('/db', async (req, res) => {
try {
const tmp = await Data.find()
res.send(tmp)
} catch (error) {
res.sendStatus(500)
}
})
app.get('*', (req, res) => {
res.sendFile(__dirname + '/src/error.html')
})
const start = async () => {
await con(process.env.MONGODB_URL);
app.listen(PORT, () => {
console.log('server runs');
})
}
start();