forked from Sahil1786/Petari
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
733 lines (572 loc) · 27.5 KB
/
app.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
require('dotenv').config();
const express = require("express");
const bodyParser = require("body-parser");
const path = require('path');
const app = express();
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const saltRounds = 10;
const nodemailer = require("nodemailer");
const moment = require('moment');
const hbs = require('nodemailer-express-handlebars');
const jwt = require("jsonwebtoken");
const flash = require('express-flash');
const Admin=require("./model/admin")
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
const NGO=require("./model/ngo")
const isAdmin=require("./middleware/isAdmin");
// const User=require("./model/user")
const Query = require('./model/query'); // Adjust the path based on your project structure
// app.use(flash());
app.set('view engine', 'ejs');
const transporter = nodemailer.createTransport({
service:'gmail',
host: "smtp.gmail.com",
port: 465,
secure: true,
auth: {
user: process.env.mail_id,
pass: process.env.pass_id
},
});
const handlebarOptions = {
viewEngine: {
extName: ".handlebars",
partialsDir: path.resolve('./views'),
defaultLayout: false,
},
viewPath: path.resolve('./views'),
extName: ".handlebars",
}
transporter.use('compile', hbs(handlebarOptions));
transporter.verify().then(console.log).catch(console.error);
app.locals.moment = moment;
mongoose.connect('mongodb://127.0.0.1:27017/PetariDB')
.then(() => {
console.log("Database Connected");
})
.catch((err) => {
console.log(err.message);
});
app.get("/", function (req, res) {
res.render("index");
});
app.get("/user_login", function (req, res) {
res.render("user_login");
});
app.get("/Ngo_login", function (req, res) {
res.render("NGO_login");
});
app.get("/admin_login", function (req, res) {
res.render("admin_login");
});
app.get("/User_singUp", function (req, res) {
res.render("User_singUp");
});
app.get("/success", function (req, res) {
res.render("success");
});
app.post("/", async function (req, res) {
try {
const newQuery = new Query({
name: req.body.Fname,
email: req.body.Email,
subject: req.body.sub,
message: req.body.sms,
});
await newQuery.save();
res.status(200).send("Successfully Received Message... Thank You!");
console.log(newQuery);
} catch (error) {
console.error(error);
res.status(500).send("Internal Server Error");
}
});
const userSchema = new mongoose.Schema({
// username: {
// type: String,
// unique: true,
// required: true,
// },
email: String,
password: String,
fullName: String,
address: String,
Mobile: Number,
dob: String,
gender: {
type: String,
enum: ['male', 'female', 'other']
},
flatNo: { type: String },
addressLine1: { type: String },
addressLine2: { type: String },
city: { type: String },
state: { type: String },
zip: { type: String },
foodInventory: [
{
foodItem: { type: String },
quantity: { type: Number }
}
]
// googleId: String,
// profile: String,
});
const User = new mongoose.model("User", userSchema);
// user Registration
app.post("/User_singUp", async function (req, res) {
const { username } = req.body;
try {
// Check if the email already exists
const existingUser = await User.findOne({ email: username }).exec();
if (existingUser) {
// Email already exists, handle accordingly (e.g., show an error message)
return res.render("registrationError", { message: 'Email is already registered' });
}
// Email does not exist, proceed with user registration
const hash = await bcrypt.hash(req.body.password, saltRounds);
const newUser = new User({
username: username,
fullName: req.body.fname,
Mobile: req.body.phn,
address: req.body.address,
dob: req.body.dob,
gender: req.body.gender,
email: username,
password: hash
});
await newUser.save()
.then((user) => {
let mailOptions = {
to: user.email,
subject: 'Welcome To Petari',
template: 'Email.template',
context: {
user: {
fname: user.fullName,
_id: user._id,
username: user.fullName,
email: user.email
},
year: new Date().getFullYear()
},
attachments: [{
filename: 'logo.png',
path: path.join(__dirname, 'public', 'img', 'logo.png'),
cid: 'logo'
}]
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
})
return res.render("UserDashBoard", {
fullName: req.body.fname,
email: username,
phoneNo: req.body.phn,
address: req.body.address
// Do not include 'profile' here unless it's relevant to registration
});
} catch (error) {
console.error('Error during user registration:', error);
return res.status(500).send('Internal Server Error');
}
});
// user login
app.post("/login", async function (req, res) {
const { username, password } = req.body;
try {
const foundUser = await User.findOne({ email: username });
if (!foundUser) {
return res.render("loginError", { message: 'User not found' });
}
const result = await bcrypt.compare(password, foundUser.password);
if (result) {
return res.render("UserDashBoard" , {fullName :foundUser.fullName,email :foundUser.email,phoneNo :foundUser.Mobile,address :foundUser.address});
} else {
return res.render("loginError", { message: 'Incorrect password' });
}
} catch (error) {
console.error('Error during login:', error);
return res.status(500).send('Internal Server Error');
}
});
app.route("/forgot-password")
.get(async (req, res) => {
res.render("forget-password");
})
.post(async (req, res) => {
const { email } = req.body;
try {
const user = await User.findOne({ email });
if (!user) {
return res.send("User Not Exist");
}
// Generate a reset token and save it to the user
const resetToken = jwt.sign({ email: user.email }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: "1h" });
user.resetTokenExpiration = Date.now() + 300000; // 5 minutes
await user.save();
// Send the reset link to the user via email
const resetLink = `http://localhost:3000/reset-password?email=${encodeURIComponent(user.email)}&token=${encodeURIComponent(resetToken)}`;
; // Replace with the actual path to your logo
console.log(resetLink);
const mailOptions = {
to: user.email,
subject: 'Password Reset',
template: 'reset-password', // Use the Handlebars template
context: {
user: {
fname: user.fullName,
_id: user._id,
username: user.username,
email: user.email
},
resetLink,
},
attachments: [{
filename: 'logo.png',
path: path.join(__dirname, 'public', 'img', 'logo.png'),
cid: 'logo'
}]
};
console.log('User email:', user.email);
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error(error);
return res.status(500).send("Error sending reset email");
}
console.log(`Reset email sent: ${info.response}`);
res.send("Password reset link sent successfully");
});
} catch (error) {
console.error(error);
res.status(500).send("Internal Server Error");
}
});
app.route("/reset-password")
.get(async (req, res) => {
const { email, token } = req.query;
try {
const user = await User.findOne({ email, resetToken: token, resetTokenExpiration: { $gt: Date.now() } });
if (!user) {
return res.status(400).send("Invalid or expired reset token");
}
// Verify the token
try {
const decodedToken = jwt.verify(token, process.env.ACCESS_TOKEN_SECRET);
// Process the decoded token (e.g., extract information from it)
console.log(decodedToken);
// Continue with the reset-password logic
res.render("reset-password", { email, token });
} catch (error) {
// Handle JWT verification errors
console.error('JWT verification error:', error.message);
// You might want to send an error response or redirect the user
res.status(401).send('Unauthorized');
}
} catch (error) {
console.error(error);
res.status(500).send("Internal Server Error");
}
})
.post(async (req, res) => {
const { email, token, newPassword } = req.body;
try {
// Verify the token again
const user = await User.findOne({ email, resetToken: token, resetTokenExpiration: { $gt: Date.now() } });
if (!user) {
return res.status(400).send("Invalid or expired reset token");
}
try {
const decodedToken = jwt.verify(token, process.env.ACCESS_TOKEN_SECRET);
// Process the decoded token (e.g., extract information from it)
console.log(decodedToken);
// Update the user's password and reset the resetToken fields
const hash = await bcrypt.hash(newPassword, saltRounds);
user.password = hash;
user.resetToken = null;
user.resetTokenExpiration = null;
await user.save();
res.redirect("/login"); // Redirect to login page or any other desired page
} catch (error) {
// Handle JWT verification errors
console.error('JWT verification error:', error.message);
// You might want to send an error response or redirect the user
res.status(401).send('Unauthorized');
}
} catch (error) {
console.error(error);
res.status(500).send("Internal Server Error");
}
});
// extra details added for the user
app.post('/add-details', async (req, res) => {
try {
// Find the user by their email
let user = await User.findOne({ email: req.body.email });
// If the user exists, update their details
if (user) {
// Update the user's details
user.flatNo = req.body.flatNo;
user.addressLine1 = req.body.addressLine1;
user.addressLine2 = req.body.addressLine2;
user.city = req.body.city;
user.state = req.body.state;
user.zip = req.body.zip;
user.foodInventory.push({ foodItem: req.body.foodItem, quantity: req.body.quantity });
// Save the updated user document
await user.save();
res.status(200).json({ message: 'Details added successfully' });
} else {
res.status(404).json({ error: 'User not found' });
}
} catch (error) {
console.error('Error adding details:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
const problem=require("./model/query")
const ad = Admin({username:"sahilkaitha@gmail.com",password:"123",fullName:"Sahil Hossain",Mobile:"9635955320"})
ad.save()
// admin code
app.post('/approve-ngo/:id', async (req, res)=> {
const ngoId = req.params.id;
try {
const ngo = await NGO.findById(ngoId);
if (!ngo) {
return res.status(404).json({ error: "NGO not found" });
}
// Update the NGO's approval status
ngo.approved = true;
await ngo.save();
// Send an email to the NGO with the approved details
let mailOptions = {
to: ngo.username,
subject: 'NGO Registration Approved',
text: 'Your NGO registration has been approved. You can now login to your account.',
// Include any necessary information in the email body
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
res.status(200).json({ message: "NGO approved successfully" });
} catch (error) {
console.error("Error approving NGO:", error);
res.status(500).json({ error: "Internal server error" });
}
});
app.post("/admin-login", async (req, res) => {
const username = req.body.username;
const password = req.body.password;
const admin = await Admin.findOne({ username: username, password: password });
try {
const dooner = await User.find(); // Assuming User is your Mongoose model for users
const ngo=await NGO.find()
const query1 = await problem.find();
res.render("Admin_Dashboard", {
name: admin.fullName,
email: admin.fullName,
mobile:admin.Mobile,
username:admin.username,
id: admin._id,
NGOname: ngo,
Donername: dooner,
UserName: "sahil114",
complain:query1
});
} catch (err) {
console.error(err);
res.status(500).send("An internal server error occurred.");
}
});
app.get("/admin-logout", function (req, res) {
return res.redirect("/");
});
app.get("/Ngo-Registration",async(req,res)=>{
res.render("NGO-Registration")
});
app.post("/NGO-Registarion", async (req, res) => {
// Check if the NGO already exists
const existingNGO = await NGO.findOne({ username: req.body.username });
if (existingNGO) {
return res.status(400).json({ error: 'NGO already exists' });
}
// Create a new NGO registration
const newNGO = new NGO({
username: req.body.username,
password: req.body.password,
NGOName: req.body.NGOName,
Mobile: req.body.Mobile,
NgoID: req.body.NgoID,
NgoLocation: req.body.NgoLocation,
approved: false
});
// Save the new NGO to the database
try {
// Save the new NGO to the database
await newNGO.save();
// Send an email to the admin for approval
let mailOptions = {
to:newNGO.username, // Admin's email address
subject: 'New NGO Registration',
text: 'A new NGO registration is pending approval. Login to the admin panel to review and approve.',
// Include any necessary information in the email body
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
console.log('NGO registration request sent for approval');
res.status(200).json({ message: 'NGO registration request sent for approval' });
} catch (err) {
console.error('Error creating NGO:', err);
res.status(500).json({ error: 'Internal server error' });
}
// try {
// await newNGO.save();
// let mailOptions = {
// to: newNGO.username,
// subject: 'Welcome To Petari',
// template: 'Email.template',
// context: {
// ngo: {
// ngoName: newNGO.name,
// _id: newNGO._id,
// username: newNGO.password,
// },
// year: new Date().getFullYear()
// },
// attachments: [{
// filename: 'logo.png',
// path: path.join(__dirname, 'public', 'img', 'logo.png'),
// cid: 'logo'
// }]
// };
// transporter.sendMail(mailOptions, function(error, info){
// if (error) {
// console.log(error);
// } else {
// console.log('Email sent: ' + info.response);
// }
// });
// console.log('NGO registered successfully');
// res.status(200).json({ message: 'NGO registration received. It will be reviewed by the admin.' });
// } catch (err) {
// console.error('Error creating NGO:', err);
// res.status(500).json({ error: 'Internal server error' });
// }
// newNGO.save()
// .then((ngo) => {
// let mailOptions = {
// to: ngo.username,
// subject: 'Welcome To Petari',
// template: 'Email.template',
// context: {
// ngo: {
// ngoName: ngo.name,
// _id: ngo._id,
// username: ngo.password,
// },
// year: new Date().getFullYear()
// },
// attachments: [{
// filename: 'logo.png',
// path: path.join(__dirname, 'public', 'img', 'logo.png'),
// cid: 'logo'
// }]
// };
// transporter.sendMail(mailOptions, function(error, info){
// if (error) {
// console.log(error);
// } else {
// console.log('Email sent: ' + info.response);
// }
// });
// console.log('NGO registered successfully');
// res.status(200).json({ message: 'NGO registered successfully' });
// })
// .catch((err) => {
// console.error('Error creating NGO:', err);
// res.status(500).json({ error: 'Internal server error' });
// });
});
// Assume you have a route for rendering the admin dashboard
// Assuming `pendingNGOs` is an array of pending NGOs
app.get("/admin-dashboard", async function (req, res) {
try {
const pendingNGOs = await NGO.find({ status: 'pending' });
res.render("admin_dashboard", { pendingNGOs });
} catch (error) {
console.error(error);
res.status(500).send("Internal Server Error");
}
});
const Ngo=require("./model/ngo")
app.post("/Ngo-login",async(req,res)=>{
const username = req.body.username;
const password = req.body.password;
const ngo = await Ngo.findOne({ username: username, password: password });
try {
const dooner = await User.find(); // Assuming User is your Mongoose model for users
res.render("NGO-Dashboard", {
fullName: ngo.NGOName,
email: ngo.username,
id: ngo.NgoID,
phoneNo:ngo.Mobile,
address :ngo.NgoLocation,
Donation : dooner,
Pickup : dooner,
complain: ""
});
} catch (err) {
console.error(err);
res.status(500).send("An internal server error occurred.");
}
})
// user delete from the databse
app.post("/delete-details", async (req, res) => {
try {
// Find the user by their email
let user = await User.findOne({ email: req.body.email });
// If the user exists, delete their details
if (user) {
// Update the user's details
user.flatNo = "";
user.addressLine1 = "";
user.addressLine2 = "";
user.city = "";
user.state = "";
user.zip = "";
user.foodInventory = [];
// Save the updated user document
await user.save();
res.status(200).json({ message: 'Details deleted successfully' });
} else {
res.status(404).json({ error: 'User not found' });
}
} catch (error) {
console.error('Error deleting details:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.get("/logout", function (req, res) {
return res.redirect("/");
});
// server rendering
// server rendiring
app.listen( process.env.port|| 3000,function(){
console.log("server is running on port 3000 ");
});