-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
182 lines (158 loc) · 8.47 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
const express = require("express");
const router = express.Router();
// const User = require('../models/User') // This line is commented out, possibly unused
const Member = require('../models/Member'); // Importing Member model
const { body, validationResult } = require('express-validator'); // Importing express-validator for validation
const bcrypt = require('bcryptjs'); // Importing bcryptjs for password hashing
const jwt = require('jsonwebtoken'); // Importing jsonwebtoken for authentication
const fetchuser = require("../middleware/fetchuser"); // Importing custom middleware
var nodemailer = require('nodemailer'); // Importing nodemailer for sending emails
const MyEmailId = process.env.BASE_EMAIL; // Your email password
const MyPassword = process.env.BASE_PASSWORD; // Your email address
const Host = process.env.HOST_NAME
const JWT_SECRET = process.env.JWT_SECRET; // Secret key for JWT authentication
let success = false; // Flag for API success
// Route to get user details after authentication
router.post('/getuser', fetchuser, async (req, res) => {
try {
const userid = req.user.id;
const user = await Member.findById(userid).select("-password");
success = true; // Set success flag to true
res.json({ success, user }); // Send success flag and user details in response
} catch (error) {
console.error(error.message); // Log error message
res.status(500).send('Internal server Error Occurred'); // Send internal server error response
}
});
// Route to reset password : Login required
router.put('/resetPassword/:id', async (req, res) => {
try {
const salt = await bcrypt.genSalt(10); // Generate salt for password hashing
const secPass = await bcrypt.hash(req.body.password, salt); // Hash password
const newdprs = { password: secPass }; // New password object
let authentic = await Member.findById(req.params.id); // Find user by id
if (!authentic) {
return res.status(404).send({ Error: "Project Not found" }); // Send error response if user not found
}
let member = await Member.findByIdAndUpdate(req.params.id, { $set: newdprs }, { new: true }); // Update user password
success = true; // Set success flag to true
res.send({ "success": "Project has been Edited successfully", success }); // Send success message in response
} catch (error) {
console.error(error.message); // Log error message
res.status(500).json({ success, Error: 'Internal server Error Occurred' }); // Send internal server error response
}
});
// Route for user's Authenticate : No login required
router.post('/login', [
body('email', 'Enter a valid Email').isEmail(),
body('password', 'Password can not be blank').exists()
], async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() }); // Send validation errors if any
}
const { email, password } = req.body;
try {
let user = await Member.findOne({ email }); // Find user by email
if (!user) {
return res.status(400).json({ errors: "Please try to login correct credentials" }); // Send error response if user not found
}
const passwordCompare = await bcrypt.compare(password, user.password); // Compare passwords
if (!passwordCompare) {
return res.status(400).json({ errors: "Please try to login correct credentials" }); // Send error response if passwords don't match
}
const data = {
id: user.id
};
const authToken = jwt.sign(data, JWT_SECRET); // Generate authentication token
success = true; // Set success flag to true
res.json({ success, authToken }); // Send success flag and authentication token in response
} catch (error) {
console.error(error.message); // Log error message
res.status(500).send('Internal server Error Occurred'); // Send internal server error response
}
});
// Route for resetting password via email
router.post('/login-reset-password', async (req, res) => {
const { email } = req.body;
try {
const oldUser = await Member.findOne({ email }); // Find user by email
if (!oldUser) {
return res.status(400).json({ errors: "Please try to login correct credentials" }); // Send error response if user not found
}
const secret = JWT_SECRET + oldUser.password; // Generate secret key
const token = jwt.sign({ email: oldUser.email, id: oldUser._id }, secret, { expiresIn: '5m' }); // Generate token with expiration
const link = `${Host}/api/auth/reset-password/${oldUser._id}/${token}`; // Reset password link
try {
var transporter = nodemailer.createTransport({
// Use for TESTING BY mailosaur.com - mail tester
// host: 'smtp.mailosaur.net',
// port: 587,
// secure: false,
// Use for original email and password
service: 'gmail',
auth: {
user: MyEmailId,
pass: MyPassword
}
});
var mailOptions = {
from: 'youremail@gmail.com',
to: `${email},${oldUser.alterEmail}`,
subject: 'DPRS RESET PASSWORD LINK',
text: `Hello ${oldUser.firstName} ${oldUser.lastName}, \n\nYou have requested to reset your DPRS (Daily Project Report System) password. Please use the following link to reset your password: \n\nDPRS RESET LINK: ${link} \n\nPlease note that this link is valid for 5 minutes only for security reasons. If you did not request this password reset or believe this to be a mistake, you can safely ignore this email. \n\nThank you. \n\nBest regards, \nDPRS TEAM \n\n`
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
success = true; // Set success flag to true
}
});
res.send({ success }); // Send success response
} catch (error) {
res.send({ success, error }); // Send error response
}
} catch (error) {
console.error(error.message); // Log error message
res.status(500).send('Internal server Error Occurred'); // Send internal server error response
}
});
// Route for rendering reset password page
router.get('/reset-password/:id/:token', async (req, res) => {
const { id, token } = req.params;
try {
const oldUser = await Member.findOne({ _id: id });
if (!oldUser) {
return res.status(400).json({ errors: "Please try to login correct credentials" }); // Send error response if user not found
}
const secret = JWT_SECRET + oldUser.password; // Generate secret key
const verify = jwt.verify(token, secret); // Verify token
res.render("index", { email: verify.email, status: "Not Verified" }); // Render reset password page
} catch (error) {
console.error(error.message); // Log error message
res.status(500).send('Internal server Error Occurred'); // Send internal server error response
}
});
// Route for handling password reset
router.post('/reset-password/:id/:token', async (req, res) => {
const { id, token } = req.params;
const { password } = req.body;
try {
const oldUser = await Member.findOne({ _id: id });
if (!oldUser) {
return res.status(400).json({ errors: "Please try to login correct credentials" }); // Send error response if user not found
}
const secret = JWT_SECRET + oldUser.password; // Generate secret key
const verify = jwt.verify(token, secret); // Verify token
const salt = await bcrypt.genSalt(10); // Generate salt for password hashing
const secPass = await bcrypt.hash(password, salt); // Hash new password
let login = await Member.findByIdAndUpdate(id, { $set: { password: secPass } }, { new: true }); // Update user password
res.render("index", { email: verify.email, status: "verified" }); // Render index page with verification status
} catch (error) {
console.error(error.message); // Log error message
res.status(500).send('Internal server Error Occurred'); // Send internal server error response
}
});
module.exports = router;