-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
2378 lines (2048 loc) · 68.4 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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from 'express';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import ejs from "ejs";
import path from "path";
import bodyParser from "body-parser";
import dotenv from "dotenv";
import crypto from "crypto";
import PDFDocument from "pdfkit";
import * as fs from "fs/promises";
import Razorpay from "razorpay";
import mongoose from 'mongoose';
import multer from 'multer';
import { createWriteStream } from 'fs';
import numberToWords from 'number-to-words';
import session from 'express-session';
import passport from 'passport';
import passportLocalMongoose from 'passport-local-mongoose';
import findOrCreate from 'mongoose-findorcreate';
import nodemailer from "nodemailer";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const app = express();
const publicRouter = express.Router();
const adminRouter = express.Router();
app.use(bodyParser.urlencoded({ extended: true }));
let storage = multer.diskStorage({
destination: 'public/images/',
filename: (req, file, cb) => {
cb(null, file.originalname)
}
})
let upload = multer({
storage: storage
})
dotenv.config();
app.use(session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect(process.env.DATABASE, {
// useNewUrlParser: true,
// useUnifiedTopology: true,
});
const conn = mongoose.connection;
conn.once('open', () => {
app.listen(10000, () => {
console.log('Server is running on port 10000');
});
});
const ngoPageSchema = new mongoose.Schema({
page_name: { type: String, required: true },
element_name: { type: String, required: true },
top_image: String,
top_title: { type: String, required: false },
top_description: { type: String, required: false },
content: [{
content_element_name: { type: String, required: true },
content_title: { type: String, required: false },
content_description: { type: String, required: false },
content_images: [String],
}],
dynamicProperties: mongoose.Schema.Types.Mixed,
});
const donationDetailsSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true },
phoneNo: { type: Number, required: true },
country: { type: String, required: true },
state: { type: String, required: true },
address: { type: String, required: true },
amount: { type: Number, required: true },
razorpay_order_id: { type: String, required: true },
razorpay_payment_id: { type: String, required: true },
razorpay_signature: { type: String, required: true },
date: { type: Date, required: true },
time: { type: Date, required: true },
dynamicProperties: mongoose.Schema.Types.Mixed,
});
const slideShowSchema = new mongoose.Schema({
page_name: { type: String, required: true },
element_name: { type: String, required: true },
title: { type: String},
content: [{
content_element_name: {type: String},
content_images: [String],
}],
dynamicProperties: mongoose.Schema.Types.Mixed,
});
const userSchema = new mongoose.Schema ({
name: String,
email: String,
password: String,
googleId: String,
secret: String,
resetPasswordToken: String,
resetPasswordExpires: Date,
});
userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);
const User = new mongoose.model("User", userSchema);
const NgoPage = mongoose.model('NgoPage', ngoPageSchema, 'NgoPage');
// console.log('Model collection name:', NgoPage.collection.name);
const donationDetails = mongoose.model('donationDetails', donationDetailsSchema, 'donationDetails');
// console.log('Model collection name:', donationDetails.collection.name);
const slideShowImages = mongoose.model('slideShowImages', slideShowSchema, 'slideShowImages');
// console.log('Model collection name:', slideShowImages.collection.name);
app.use(express.static(__dirname));
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
app.engine('ejs', ejs.renderFile);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());
var instance = new Razorpay({
key_id: process.env.RAZORPAY_KEY_ID,
key_secret: process.env.RAZORPAY_KEY_SECRET,
});
// For Forgot password email
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL_USERNAME,
pass: process.env.EMAIL_PASSWORD,
},
});
passport.use(User.createStrategy());
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(async function(id, done) {
try {
const user = await User.findById(id).exec();
done(null, user);
} catch (err) {
done(err, null);
}
});
//Below is NGO website visible to all code
//Below is home page code **************************************************
publicRouter.get('/', async (req, res) => {
try {
const home_page_data = await NgoPage.findOne({
page_name: 'home_page',
});
const home_page_data2 = await NgoPage.findOne({
page_name: 'home_page',
element_name: 'story',
});
const home_page_images_data = await slideShowImages.findOne({
page_name: 'home_page',
});
// Fetch data for the header
const header_data = await NgoPage.findOne({
page_name: 'header_page',
});
// Fetch data for the social media
const social_media_data = await NgoPage.findOne({
page_name: 'social_media_page',
});
// Fetch data for the footer
const footer_data = await NgoPage.findOne({
page_name: 'footer_page',
});
const contact_data = await NgoPage.findOne({
page_name: 'contact_us_page',
});
// console.log('Retrieved data:', home_page_data);
res.locals.data = {
homeData: home_page_data,
storyData: home_page_data2,
headerData: header_data,
socialMediaData: social_media_data,
footerData: footer_data,
contactUsData: contact_data,
homeImages: home_page_images_data,
};
if (home_page_data) {
res.render('index', { data: res.locals.data });
} else {
res.status(404).send('Page not found');
}
} catch (err) {
console.error('Error fetching page data:', err.message);
res.status(500).send('Internal Server Error');
}
});
publicRouter.get('/public/ourstory', async (req, res) => {
try {
const about_us_page_data = await NgoPage.findOne({
page_name: 'about_us_page',
});
// Fetch data for the header
const header_data = await NgoPage.findOne({
page_name: 'header_page',
});
// Fetch data for the social media
const social_media_data = await NgoPage.findOne({
page_name: 'social_media_page',
});
// Fetch data for the footer
const footer_data = await NgoPage.findOne({
page_name: 'footer_page',
});
const contact_data = await NgoPage.findOne({
page_name: 'contact_us_page',
});
// console.log('Retrieved data:', about_us_page_data);
res.locals.data = {
aboutUsData: about_us_page_data,
headerData: header_data,
socialMediaData: social_media_data,
footerData: footer_data,
contactUsData: contact_data,
};
if (about_us_page_data) {
res.render('about', { data: res.locals.data });
} else {
res.status(404).send('Page not found');
}
} catch (err) {
console.error('Error fetching page data:', err.message);
res.status(500).send('Internal Server Error');
}
});
publicRouter.get('/public/vision', async (req, res) => {
try {
const vision_page_data = await NgoPage.findOne({
page_name: 'vision_and_mission_page',
});
// Fetch data for the header
const header_data = await NgoPage.findOne({
page_name: 'header_page',
});
// Fetch data for the social media
const social_media_data = await NgoPage.findOne({
page_name: 'social_media_page',
});
// Fetch data for the footer
const footer_data = await NgoPage.findOne({
page_name: 'footer_page',
});
const contact_data = await NgoPage.findOne({
page_name: 'contact_us_page',
});
// console.log('Retrieved data:', vision_page_data);
res.locals.data = {
visionData: vision_page_data,
headerData: header_data,
socialMediaData: social_media_data,
footerData: footer_data,
contactUsData: contact_data,
};
if (vision_page_data) {
res.render('vision', { data: res.locals.data });
} else {
res.status(404).send('Page not found');
}
} catch (err) {
console.error('Error fetching page data:', err.message);
res.status(500).send('Internal Server Error');
}
});
publicRouter.get('/public/activity', async (req, res) => {
// res.render('activity');
try {
const activity_page_data = await NgoPage.findOne({
page_name: 'activity_page',
});
// Fetch data for the header
const header_data = await NgoPage.findOne({
page_name: 'header_page',
});
// Fetch data for the social media
const social_media_data = await NgoPage.findOne({
page_name: 'social_media_page',
});
// Fetch data for the footer
const footer_data = await NgoPage.findOne({
page_name: 'footer_page',
});
const contact_data = await NgoPage.findOne({
page_name: 'contact_us_page',
});
// console.log('Retrieved data:', activity_page_data);
res.locals.data = {
activityData: activity_page_data,
headerData: header_data,
socialMediaData: social_media_data,
footerData: footer_data,
contactUsData: contact_data,
};
if (activity_page_data) {
res.render('activity', { data: res.locals.data });
} else {
res.status(404).send('Page not found');
}
} catch (err) {
console.error('Error fetching page data:', err.message);
res.status(500).send('Internal Server Error');
}
});
publicRouter.get('/public/gallery', async (req, res) => {
// res.render('gallery');
try {
const gallery_page_data = await NgoPage.findOne({
page_name: 'gallery_page',
});
// Fetch data for the header
const header_data = await NgoPage.findOne({
page_name: 'header_page',
});
// Fetch data for the social media
const social_media_data = await NgoPage.findOne({
page_name: 'social_media_page',
});
// Fetch data for the footer
const footer_data = await NgoPage.findOne({
page_name: 'footer_page',
});
const contact_data = await NgoPage.findOne({
page_name: 'contact_us_page',
});
// console.log('Retrieved data:', gallery_page_data);
res.locals.data = {
galleryData: gallery_page_data,
headerData: header_data,
socialMediaData: social_media_data,
footerData: footer_data,
contactUsData: contact_data,
};
if (gallery_page_data) {
res.render('gallery', { data: res.locals.data });
} else {
res.status(404).send('Page not found');
}
} catch (err) {
console.error('Error fetching page data:', err.message);
res.status(500).send('Internal Server Error');
}
});
publicRouter.get('/public/join', async (req, res) => {
// res.render('activity');
try {
const join_page_data = await NgoPage.findOne({
page_name: 'join_us_page',
});
// Fetch data for the header
const header_data = await NgoPage.findOne({
page_name: 'header_page',
});
// Fetch data for the social media
const social_media_data = await NgoPage.findOne({
page_name: 'social_media_page',
});
// Fetch data for the footer
const footer_data = await NgoPage.findOne({
page_name: 'footer_page',
});
const contact_data = await NgoPage.findOne({
page_name: 'contact_us_page',
});
// console.log('Retrieved data:', join_page_data);
res.locals.data = {
joinData: join_page_data,
headerData: header_data,
socialMediaData: social_media_data,
footerData: footer_data,
contactUsData: contact_data,
};
if (join_page_data) {
res.render('join', { data: res.locals.data });
} else {
res.status(404).send('Page not found');
}
} catch (err) {
console.error('Error fetching page data:', err.message);
res.status(500).send('Internal Server Error');
}
});
publicRouter.get("/public/donate", async (req, res) => {
// res.sendFile(__dirname + "/index.html");
try {
const donate_page_data = await NgoPage.findOne({
page_name: 'donate_page',
});
// Fetch data for the header
const header_data = await NgoPage.findOne({
page_name: 'header_page',
});
// Fetch data for the social media
const social_media_data = await NgoPage.findOne({
page_name: 'social_media_page',
});
// Fetch data for the footer
const footer_data = await NgoPage.findOne({
page_name: 'footer_page',
});
const contact_data = await NgoPage.findOne({
page_name: 'contact_us_page',
});
// console.log('Retrieved data:', donate_page_data);
res.locals.data = {
donateData: donate_page_data,
headerData: header_data,
socialMediaData: social_media_data,
footerData: footer_data,
contactUsData: contact_data,
};
if (footer_data) {
res.render('donate', { data: res.locals.data });
} else {
res.status(404).send('Page not found');
}
} catch (err) {
console.error('Error fetching page data:', err.message);
res.status(500).send('Internal Server Error');
}
});
let globalDonarDetails;
publicRouter.post("/payNow", (req, res) => {
const { amount, name, donorDetails } = req.body;
globalDonarDetails = donorDetails;
// console.log("donate button pressed");
if (!amount) {
return res.status(400).send("Amount is required.");
}
// Ensure that donorDetails is correctly extracted
// console.log("donorDetails:", donorDetails);
var options = {
amount: amount * 100, // Amount in the smallest currency unit (paise)
currency: "INR",
receipt: `order_rcptid_${Date.now()}`,
};
instance.orders.create(options, function (err, order) {
if (err) {
console.error("Error creating order:", err);
res.status(500).send("Error creating order");
} else if (order && order.id) {
// console.log("Order created successfully:", order.id);
res.send({ orderId: order.id });
} else {
console.error("Unexpected response from Razorpay:", order);
res.status(500).send("Unexpected response from Razorpay");
}
});
});
publicRouter.post("/api/payment/verify", async (req, res) => {
let body = req.body.razorpay_order_id + "|" + req.body.razorpay_payment_id;
var expectedSignature = crypto.createHmac("sha256", process.env.RAZORPAY_KEY_SECRET)
.update(body)
.digest("hex");
var response = { signatureIsValid: false };
if (expectedSignature === req.body.razorpay_signature) {
// console.log("SAHIL",globalDonarDetails);
const donorData = {
name: globalDonarDetails.name,
email: globalDonarDetails.email,
phoneNo: globalDonarDetails.mobileNo,
country: globalDonarDetails.country,
state: globalDonarDetails.state,
address: globalDonarDetails.address,
amount: globalDonarDetails.amount,
razorpay_order_id: req.body.razorpay_order_id,
razorpay_payment_id: req.body.razorpay_payment_id,
razorpay_signature: req.body.razorpay_signature,
time: Date.now(),
date: Date.now(),
};
const newDonor = new donationDetails(donorData);
// console.log('sahil below is donar data:', donorData);
await newDonor.save();
response = { signatureIsValid: true };
// res.render("thankyou.ejs");
}
res.send(response);
});
publicRouter.get('/thankyou', async (req, res) => {
// res.render('thankyou');
try {
// Fetch data for the header
const header_data = await NgoPage.findOne({
page_name: 'header_page',
});
// Fetch data for the social media
const social_media_data = await NgoPage.findOne({
page_name: 'social_media_page',
});
// Fetch data for the footer
const footer_data = await NgoPage.findOne({
page_name: 'footer_page',
});
const contact_data = await NgoPage.findOne({
page_name: 'contact_us_page',
});
// console.log('Retrieved data:', header_data);
res.locals.data = {
headerData: header_data,
socialMediaData: social_media_data,
footerData: footer_data,
contactUsData: contact_data,
};
if (header_data) {
res.render('thankyou', { data: res.locals.data });
} else {
res.status(404).send('Page not found');
}
} catch (err) {
console.error('Error fetching page data:', err.message);
res.status(500).send('Internal Server Error');
}
})
publicRouter.get('/generatePDF', async (req, res) => {
const doc = new PDFDocument();
const writeStream = createWriteStream('thankyou.pdf');
// Handle the finish event of the writeStream
writeStream.on('finish', async () => {
// console.log('PDF writing has finished');
res.download('thankyou.pdf'); // Offer the generated PDF for download
});
// Pipe the PDF output to the writeStream
doc.pipe(writeStream);
// Set the font for the entire document
doc.font('Helvetica');
// Center the logo horizontally
const logoX = 200;
doc.image("./public/images/ngo_logo_new.png", logoX, 0, { width: 200 });
doc.moveDown(10); // Some space
// Add NGO name centered, in bold and large size
// doc.fontSize(26).font('Helvetica-Bold').text('Happy Day Foundation', { align: 'center' });
// doc.moveDown(1); // Some space
// Add a small description of the NGO
doc.fontSize(14).text('A non-profit organization dedicated to making the world a better place for underprivileged children.', { align: 'center' });
doc.moveDown(2); // Some space
// Donor details
doc.fontSize(18).text('Donor Details:', { align: 'center' });
doc.fontSize(14).text('Name: ' + req.query.userName);
doc.text('Donation Amount: ' + req.query.donationAmount + ' INR');
const donationAmountInWords = numberToWords.toWords(req.query.donationAmount);
doc.fontSize(14).text('Amount in Text: ' + donationAmountInWords.charAt(0).toUpperCase() + donationAmountInWords.slice(1) + ' Rupees Only');
// doc.moveDown(1); // Some space
doc.fontSize(14).text('E-mail: ' + req.query.email);
doc.text('Mobile No.: ' + req.query.mobileNo);
doc.fontSize(14).text('Country: ' + req.query.country);
doc.text('State: ' + req.query.state);
doc.fontSize(14).text('Address: ' + req.query.address);
doc.moveDown(1); // Some space
// Thank the donor for their precious donation
doc.fontSize(18).text('Thank You for Your Generous Donation!', { align: 'center' });
doc.moveDown(2); // Some space
// Impact Statement
doc.fontSize(18).text('Impact of Your Donation:', { align: 'center' });
doc.fontSize(14).text('Your generous contribution plays a vital role in improving the lives of underprivileged children. At Happy Day Foundation, we are dedicated to enhancing the health and education of these young minds.', { align: 'center' });
doc.moveDown(1); // Some space
doc.fontSize(14).text('With your support, we can provide:', { align: 'left' });
doc.fontSize(14).text(' - Access to quality healthcare to ensure their well-being.', { align: 'left' });
doc.fontSize(14).text(' - Educational opportunities, including books, school supplies, and quality teaching.', { align: 'left' });
doc.moveDown(2); // Some space
// Contact Information
doc.fontSize(18).text('Contact Information:', { align: 'center' });
doc.fontSize(14).text('For inquiries and support, please feel free to contact us at:', { align: 'left' });
doc.fontSize(14).text('Email: contact@happydayfoundation.org', { align: 'left' });
doc.fontSize(14).text('Phone: +1 (123) 456-7890', { align: 'left' });
doc.fontSize(14).text('Address: 123 Sunshine Street, Cityville, Country', { align: 'left' });
doc.moveDown(1); // Some space
// Thank You
doc.fontSize(20).font('Helvetica-Bold').text('Thank You for Your Support!', { align: 'center' });
doc.end(); // Finalize the PDF
});
publicRouter.get('/public/:element_name', async (req, res) => {
try {
const elementName = req.params.element_name;
// Fetch the page details from the database based on the element_name
const pageDetails = await NgoPage.findOne({ element_name: elementName });
if (!pageDetails) {
// Handle case when the page is not found
return res.status(404).send(`404 Error ${elementName} page does not exist`);
}
// Fetch data for the header
const header_data = await NgoPage.findOne({
page_name: 'header_page',
});
// Fetch data for the social media
const social_media_data = await NgoPage.findOne({
page_name: 'social_media_page',
});
// Fetch data for the footer
const footer_data = await NgoPage.findOne({
page_name: 'footer_page',
});
const contact_data = await NgoPage.findOne({
page_name: 'contact_us_page',
});
const activityImages1 = await slideShowImages.findOne({
element_name: elementName,
});
// console.log('Retrieved data:', activityImages1);
res.locals.data = {
contentElement: pageDetails,
headerData: header_data,
socialMediaData: social_media_data,
footerData: footer_data,
contactUsData: contact_data,
activityImages:activityImages1,
};
if (pageDetails) {
res.render('new_activity_page', { data: res.locals.data });
} else {
res.status(404).send('Page not found');
}
} catch (error) {
console.error('Error:', error);
res.status(500).send('Internal Server Error');
}
});
// *********
app.get('/admin',function(req,res){
res.status(400).send(`
<html>
<head>
<script>
alert('Bad Request. Redirecting...');
window.location.href = '/';
</script>
</head>
<body>
<p>Redirecting...</p>
</body>
</html>
`);
});
// ********
// Mount the publicRouter first
app.use('/', publicRouter);
//Code completed
//Below is forgot-password code **************************************************
adminRouter.get('/forgot-password', (req, res) => {
try {
res.render('forgot-password.ejs', { error: null, success: null });
} catch (error) {
console.log(error.message);
}
});
adminRouter.post('/forgot-password', async (req, res) => {
const { email } = req.body;
try {
const user = await User.findOne({ username: email });
if (!user) {
return res.render("forgot-password", { error: "User not found", success: null });
}
// Generate a unique token for the reset link
const token = crypto.randomBytes(20).toString('hex');
// Set the token and expiration time in the user document
user.resetPasswordToken = token;
user.resetPasswordExpires = Date.now() + 3600000; // Token valid for 1 hour
await user.save();
// Create a reset password link
const resetLink = `${req.protocol}://${req.headers.host}/admin/reset-password/${token}`;
// Send an email with the reset link
await transporter.sendMail({
from: process.env.EMAIL_USERNAME,
to: email,
subject: 'Password Reset',
html: `Click <a href="${resetLink}">here</a> to reset your password.`,
});
res.render("forgot-password", { error: null, success: "Password reset email sent" });
} catch (error) {
console.error(error);
res.status(500).send('Internal Server Error');
}
});
adminRouter.get('/reset-password/:token', async (req, res) => {
const { token } = req.params;
try {
const user = await User.findOne({
resetPasswordToken: token,
resetPasswordExpires: { $gt: Date.now() },
});
if (!user) {
return res.render("reset-password", { error: "Invalid or expired reset link", success: null, token: null });
}
// If the token is valid, render the reset password view with the token
res.render("reset-password", { token, error: null, success: null });
} catch (error) {
console.error(error);
res.status(500).send('Internal Server Error');
}
});
adminRouter.post('/reset-password/:token', async (req, res) => {
const { token } = req.params;
const { newPassword } = req.body;
try {
const user = await User.findOne({
resetPasswordToken: token,
resetPasswordExpires: { $gt: Date.now() },
});
if (!user) {
return res.render("reset-password", { error: "Invalid or expired reset link", success: null });
}
// Update the user's password
user.setPassword(newPassword, async () => {
user.resetPasswordToken = undefined;
user.resetPasswordExpires = undefined;
await user.save();
// Render the login page after successful password reset
res.render("login", { error: null, success: "Password reset successfully. Please login with your new password." });
});
} catch (error) {
console.error(error);
res.status(500).send('Internal Server Error');
}
});
//Above is forgot-password code **************************************************
//Below is login code **************************************************
adminRouter.get("/login", function(req, res){
// res.render("login");
res.render("login", { error: null });
});
adminRouter.post("/login", function(req, res, next) {
const user = new User({
username: req.body.username,
password: req.body.password
});
passport.authenticate("local", function(err, user, info) {
if (err) {
console.log(err);
return next(err);
}
if (!user) {
// If authentication fails, show a popup with an error message
return res.render("login", { error: "Invalid username or password" });
}
req.login(user, function(err) {
if (err) {
console.log(err);
return next(err);
}
// If authentication succeeds, pass user information to the admin page
return res.render("admin", { user: { name: user.name, email: user.username }, success: "Login successful!" });
});
})(req, res, next);
});
//Below is register code **************************************************
adminRouter.get("/register", async function(req, res){
// res.render("register");
if (req.isAuthenticated()){
res.render('register');
} else {
// res.redirect("/admin/login");
res.status(400).send(`
<html>
<head>
<script>
alert('Unauthorized Access. Redirecting...');
window.location.href = '/';
</script>
</head>
<body>
<p>Redirecting...</p>
</body>
</html>
`);
}
});
adminRouter.post("/register", function(req, res){
// Create a user object with all necessary properties
var newUser = new User({
name: req.body.name,
username: req.body.username
});
// Use the User.register method to register the user
User.register(newUser, req.body.password, function(err, user){
if (err) {
console.log(err);
// res.redirect("/admin/register");
res.status(400).send(`
<html>
<head>
<script>
alert('Admin with same username already exists. Redirecting...');
window.location.href = '/admin/register';
</script>
</head>
<body>
<p>Redirecting...</p>
</body>
</html>
`);
} else {
passport.authenticate("local")(req, res, function(){
// res.redirect("/admin/login");
res.status(400).send(`
<html>
<head>
<script>
alert('Congratlations you are our new member, welcome to Happy Day Foundation family.');
window.location.href = '/admin/login';
</script>
</head>
<body>
<p>Redirecting...</p>
</body>
</html>
`);
});
}
});
});
//Below is logout code **************************************************
adminRouter.get("/logout", function(req, res){
req.logout(function(err) {
if (err) {
return next(err);
}
res.status(400).send(`
<html>
<head>
<script>
alert('Logged Out successfully. Redirecting...');
window.location.href = '/';
</script>
</head>
<body>
<p>Redirecting...</p>
</body>
</html>
`);
// res.redirect("/");
});
});
//Below is admin pages code **************************************************