forked from VanshKing30/FoodiesWeb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAuth.js
599 lines (518 loc) · 14.5 KB
/
Auth.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
const bcrypt = require("bcrypt");
const User = require("../models/studentLoginInfo");
const jwt = require("jsonwebtoken");
const Canteen = require("../models/canteenLoginInfo");
const Session = require("../models/session");
const Contact = require('../models/Contact');
const {
forgotPasswordToken,
verifyToken,
findUserByEmail,
findUserById,
} = require("../utils/PasswordTokenAndUser");
const nodemailer = require("nodemailer");
require("dotenv").config();
exports.studentSignup = async (req, res) => {
console.log("This is jwt", process.env.JWT_SECRET);
try {
console.log(req.body);
const { name, email, collegeName, accountType, password, confirmPassword } =
await req.body;
if (password !== confirmPassword) {
return res.status(400).json({
success: false,
message: "Password and Confirm password didn't match, try again",
});
}
const existingUser = await User.findOne({
email,
});
if (existingUser) {
return res.status(400).json({
success: false,
message: "User alredy exist",
});
}
let hashedPassword;
try {
hashedPassword = await bcrypt.hash(password, 10);
} catch (error) {
console.log(error);
return res.status(500).json({
success: false,
message: "Error in hashing password",
});
}
const user = await User.create({
name,
email,
collegeName,
accountType,
password: hashedPassword,
});
await user.save();
return res.status(200).json({
success: true,
message: "User created succesfully",
});
} catch (error) {
console.error(error);
return res.status(500).json({
success: false,
message: "USer can not be registred",
});
}
};
exports.studentLogin = async (req, res) => {
try {
console.log(req.body);
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({
success: false,
message: "Please Fill all the deatils",
});
}
let user = await User.findOne({ email });
if (!user) {
return res.status(401).json({
success: false,
message: "User is not registred",
});
}
const payload = {
email: user.email,
id: user._id,
accountType: user.accountType,
};
if (await bcrypt.compare(password, user.password)) {
let token = jwt.sign(payload, process.env.JWT_SECRET, {
expiresIn: "2h",
});
// creating a session
const session = new Session({
userId: user._id,
token,
});
await session.save();
user = user.toObject();
user.token = token;
user.password = undefined;
console.log(user);
// const options = {
// expires: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000),
// httpOnly: true,
// };
// res.cookie("token", token, options).status(200).json({
// success: true,
// token,
// user,
// message: "User logged in succesfully",
// });
// Setting cookie
res.cookie("token", token, {
httpOnly: true,
secure: true,
maxAge: 3600000,
});
res.json({
success: true,
message: "Logged in successfully",
token,
user,
});
} else {
return res.status(403).json({
success: false,
message: "Pasword Incorrect",
});
}
} catch (error) {
console.log(error);
return res.status(500).json({
success: false,
message: "Login failure",
});
}
};
// Student Logout Controller
exports.studentLogout = async (req, res) => {
try {
await User.findByIdAndUpdate(
req.user?._id,
{
$unset: {
token: 1,
},
},
{
new: true,
}
);
// const options = {
// httpOnly: true,
// };
// return res.status(200).clearCookie("token", options).json({
// success: true,
// message: "User Logged off successfully.",
// });
const token =
req.cookies?.token ||
req?.header("Authorization")?.replace("Bearer ", "");
if (token) {
await Session.findOneAndDelete({ token });
res.clearCookie("token");
}
res.status(200).json({
success: true,
message: "Logged out successfully",
});
} catch (error) {
console.log(error);
return res.status(500).json({
success: false,
message: "Logout failure",
});
}
};
// Controller for changing the student password
exports.changeStudentPassword = async (req, res) => {
const { oldPassword, newPassword } = req.body;
const user = await User.findById(req.user._id);
const isPasswordCorrect = await bcrypt.compare(oldPassword, user.password);
if (!isPasswordCorrect) {
return res.status(400).json({
success: false,
message: "Invalid old password",
});
}
const newHashedPassword = await bcrypt.hash(newPassword, 10);
user.password = newHashedPassword;
user.save();
return res.status(200).json({
success: true,
message: "Password updated successfully.",
});
};
//for canteens
exports.canteenSignup = async (req, res) => {
console.log("Received signup request with data:", req.body);
try {
const { name, email, collegeName, accountType, password } = req.body;
const existingCanteen = await Canteen.findOne({ email });
if (existingCanteen) {
console.log("User already exists with email:", email);
return res.status(400).json({
success: false,
message: "User already exists",
});
}
let hashedPassword;
try {
hashedPassword = await bcrypt.hash(password, 10);
} catch (error) {
console.error("Error in hashing password:", error);
return res.status(500).json({
success: false,
message: "Error in hashing password",
});
}
const canteen = await Canteen.create({
name,
email,
collegeName,
accountType,
password: hashedPassword,
});
// Create a token
const token = jwt.sign(
{ id: canteen._id, email: canteen.email, accountType: canteen.accountType, },
process.env.JWT_SECRET,
{
expiresIn: "1h", // Set token expiration time as needed
}
);
console.log("User created successfully with ID:", canteen._id);
return res.status(200).json({
success: true,
message: "User created successfully",
cantId: canteen._id,
token,
});
} catch (error) {
console.error("Error during user registration:", error);
return res.status(500).json({
success: false,
message: "User cannot be registered",
});
}
};
exports.canteenLogin = async (req, res) => {
try {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({
success: false,
message: "Please Fill all the deatils",
});
}
let canteen = await Canteen.findOne({
email,
});
if (!canteen) {
return res.status(401).json({
success: false,
message: " Canteen is not registred",
});
}
const payload = {
email: canteen.email,
id: canteen._id,
accountType: canteen.accountType,
};
if (await bcrypt.compare(password, canteen.password)) {
let token = jwt.sign(payload, process.env.JWT_SECRET, {
expiresIn: "2h",
});
canteen = canteen.toObject();
canteen.token = token;
console.log(canteen);
canteen.password = undefined;
console.log(canteen);
// const options = {
// expires: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000),
// httpOnly: true,
// };
// res.cookie("token", token, options).status(200).json({
// success: true,
// token,
// canteen,
// message: "Canteen logged in succesfully",
// cantId: canteen._id,
// });
// Create session
const session = new Session({
userId: canteen._id,
token,
});
await session.save();
// Set cookie
res.cookie("token", token, {
httpOnly: true,
secure: true,
maxAge: 3600000,
});
res.json({
success: true,
message: "Logged in successfully",
token,
canteen,
cantId: canteen._id,
});
} else {
return res.status(403).json({
success: false,
message: "Pasword Incorrect",
});
}
} catch (error) {
console.log(error);
return res.status(500).json({
success: false,
message: "Login failure",
});
}
};
// Canteen Logout Controller
exports.canteenLogout = async (req, res) => {
try {
await Canteen.findByIdAndUpdate(
req.user._id,
{
$unset: {
token: 1,
},
},
{
new: true,
}
);
// const options = {
// httpOnly: true,
// };
// return res.status(200).clearCookie("token", options).json({
// success: true,
// message: "Canteen User Logged off successfully.",
// });
const token =
req.cookies?.token ||
req?.header("Authorization")?.replace("Bearer ", "");
if (token) {
await Session.findOneAndDelete({ token });
res.clearCookie("token");
}
res.status(200).json({
success: true,
message: "Logged out successfully",
});
} catch (error) {
console.log(error);
return res.status(500).json({
success: false,
message: "Logout failure",
});
}
};
// Canteen Reset Password
exports.changeCanteenPassword = async (req, res) => {
const { oldPassword, newPassword } = req.body;
const user = await Canteen.findById(req.user._id);
const isPasswordCorrect = await bcrypt.compare(oldPassword, user.password);
if (!isPasswordCorrect) {
return res.status(400).json({
success: false,
message: "Invalid old password",
});
}
const newHashedPassword = await bcrypt.hash(newPassword, 10);
user.password = newHashedPassword;
user.save();
return res.status(200).json({
success: true,
message: "Password updated successfully.",
});
};
//contactUs
exports.saveContactMessage = async (req, res) => {
try {
const { name, email, message } = req.body;
if (!name || !email || !message) {
return res.status(400).send('All fields are required');
}
const newContact = new Contact({ name, email, message });
await newContact.save();
res.status(201).send('Message received');
} catch (error) {
console.error('Error saving message:', error.message, error);
res.status(500).send('Error saving message');
}
};
// verify user for reset password
exports.forgotPassword = async (req, res) => {
try {
const { email } = req.body;
const existingUser = await findUserByEmail(email);
if (!existingUser) {
return res.status(400).json({
success: false,
message: "User does not exist",
});
} else {
const tokenReturn = forgotPasswordToken(existingUser);
// const link = `http://localhost:3000/api/v1/newPassword/${existingUser._id}/${tokenReturn}`;
const link = `https://foodies-web-app.vercel.app/api/v1/newPassword/${existingUser._id}/${tokenReturn}`;
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: process.env.EMAIL,
pass: process.env.MAILPASS,
},
});
const mailOptions = {
from: process.env.EMAIL,
to: email,
subject: "Password Reset Link",
html: `
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: auto; padding: 20px; border: 1px solid #ccc; border-radius: 10px;">
<h2 style="text-align: center; color: #333;">Password Reset Request</h2>
<p style="color: #333;">Hello,</p>
<p style="color: #333;">You have requested to reset your password. Please click the button below to reset your password:</p>
<div style="text-align: center; margin: 20px 0;">
<a href="${link}" style="background-color: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;">Reset Password</a>
</div>
<p style="color: #333;">If you did not request this, please ignore this email.</p>
<p style="color: #333;">Thank you,</p>
<p style="color: #333;">FoodiesWeb</p>
<hr>
<p style="color: #999; text-align: center;">© 2024 Your Company Name. All rights reserved.</p>
</div>
`,
};
await transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
}
});
res.status(201).json({
msg: "You should receive an email",
});
}
} catch (error) {
console.error(error);
return res.status(500).json({
success: false,
message: "User verification failed",
});
}
};
//for verification of link
exports.verifyLink = async (req, res) => {
const { id, token } = req.params;
console.log(req.params);
const oldUser = await findUserById(id);
if (!oldUser) {
return res.status(404).json({
success: false,
message: "User not found!",
});
}
try {
console.log("Found user: ", oldUser);
const verify = verifyToken(oldUser, token);
console.log("VerifyToken result: ", verify);
if (verify.id === id) {
res.status(201).json({
email: verify.email,
status: "Verified",
});
} else {
res.status(201).json({
status: "Cannot Verify",
});
}
} catch (error) {
res.status(201).json({
status: "Not Verified",
});
}
};
exports.resetPassword = async (req, res) => {
const { id, token } = req.params;
const { password } = req.body;
console.log(password, " ", id, " ", token);
try {
const oldUser = await findUserById(id);
if (!oldUser) {
return res.status(404).json("User not found");
}
const verify = verifyToken(oldUser, token);
if (verify.id !== id) {
return res.status(201).json({ change: false });
}
const salt = await bcrypt.genSalt(10);
const newPassword = await bcrypt.hash(password, salt);
if (oldUser instanceof User) {
await User.findByIdAndUpdate(id, {
password: newPassword,
});
} else if (oldUser instanceof Canteen) {
await Canteen.findByIdAndUpdate(id, {
password: newPassword,
});
}
res.status(201).json({ change: true });
} catch (error) {
console.log("Error while changing password: ", error);
res.status(500).json("Some error occurred!");
}
};