Repository navigation
Expand file tree
/
Copy pathAuth.js
More file actions
288 lines (263 loc) · 8.15 KB
/
Copy pathAuth.js
File metadata and controls
288 lines (263 loc) · 8.15 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
// controllers/Auth.js
const bcrypt = require("bcrypt")
const User = require("../models/User")
const OTP = require("../models/OTP")
const jwt = require("jsonwebtoken")
const otpGenerator = require("otp-generator")
const mailSender = require("../utils/mailSender")
const { passwordUpdated } = require("../mail/templates/passwordUpdate")
const Profile = require("../models/Profile")
require("dotenv").config()
// Signup Controller for Registering USers
exports.signup = async (req, res) => {
try {
// Destructure fields from the request body
const {
firstName,
lastName,
email,
password,
confirmPassword,
accountType,
otp,
} = req.body
// Check if All Details are there or not
if (
!firstName ||
!lastName ||
!email ||
!password ||
!confirmPassword ||
!otp
) {
return res.status(403).send({
success: false,
message: "All Fields are required",
})
}
// Check if password and confirm password match
if (password !== confirmPassword) {
return res.status(400).json({
success: false,
message:
"Password and Confirm Password do not match. Please try again.",
})
}
// Check if user already exists
const existingUser = await User.findOne({ email })
if (existingUser) {
return res.status(400).json({
success: false,
message: "User already exists. Please sign in to continue.",
})
}
// Find the most recent OTP for the email
const response = await OTP.find({ email }).sort({ createdAt: -1 }).limit(1)
console.log(response)
if (response.length === 0) {
// OTP not found for the email
return res.status(400).json({
success: false,
message: "The OTP is not valid",
})
} else if (otp !== response[0].otp) {
// Invalid OTP
return res.status(400).json({
success: false,
message: "The OTP is not valid",
})
}
// Hash the password
const hashedPassword = await bcrypt.hash(password, 10)
// Create the Additional Profile For User
const profileDetails = await Profile.create({
gender: null,
dateOfBirth: null,
about: null,
contactNumber: null,
})
const user = await User.create({
firstName,
lastName,
email,
password: hashedPassword,
accountType: accountType,
additionalDetails: profileDetails._id,
image: `https://api.dicebear.com/5.x/initials/svg?seed=${firstName} ${lastName}`,
})
return res.status(200).json({
success: true,
user,
message: "User registered successfully",
})
} catch (error) {
console.error(error)
return res.status(500).json({
success: false,
message: "User cannot be registered. Please try again.",
})
}
}
// Login controller for authenticating users
exports.login = async (req, res) => {
try {
// Get email and password from request body
const { email, password } = req.body
// Check if email or password is missing
if (!email || !password) {
// Return 400 Bad Request status code with error message
return res.status(400).json({
success: false,
message: `Please Fill up All the Required Fields`,
})
}
// Find user with provided email
const user = await User.findOne({ email }).populate("additionalDetails").exec()
// If user not found with provided email
if (!user) {
// Return 401 Unauthorized status code with error message
return res.status(401).json({
success: false,
message: `User is not Registered with Us Please SignUp to Continue`,
})
}
// Generate JWT token and Compare Password
if (await bcrypt.compare(password, user.password)) {
const token = jwt.sign(
{ email: user.email, id: user._id, accountType: user.accountType },
process.env.JWT_SECRET,
{
expiresIn: "24h",
}
)
// Save token to user document in database
user.token = token
user.password = undefined
// Set cookie for token and return success response
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 Login Success`,
})
} else {
return res.status(401).json({
success: false,
message: `Password is incorrect`,
})
}
} catch (error) {
console.error(error)
// Return 500 Internal Server Error status code with error message
return res.status(500).json({
success: false,
message: `Login Failure Please Try Again`,
})
}
}
// Send OTP For Email Verification
exports.sendotp = async (req, res) => {
try {
const { email } = req.body
// Check if user is already present
// Find user with provided email
const checkUserPresent = await User.findOne({ email })
// to be used in case of signup
// If user found with provided email
if (checkUserPresent) {
// Return 401 Unauthorized status code with error message
return res.status(401).json({
success: false,
message: `User is Already Registered`,
})
}
var otp = otpGenerator.generate(6, {
upperCaseAlphabets: false,
lowerCaseAlphabets: false,
specialChars: false,
})
const result = await OTP.findOne({ otp: otp })
console.log("Result is Generate OTP Func")
console.log("OTP", otp)
console.log("Result", result)
while (result) {
otp = otpGenerator.generate(6, {
upperCaseAlphabets: false,
})
}
const otpPayload = { email, otp }
const otpBody = await OTP.create(otpPayload)
console.log("OTP Body", otpBody)
res.status(200).json({
success: true,
message: `OTP Sent Successfully`,
otp,
})
} catch (error) {
console.log(error.message)
return res.status(500).json({ success: false, error: error.message })
}
}
// Controller for Changing Password
exports.changePassword = async (req, res) => {
try {
// Get user data from req.user
const userDetails = await User.findById(req.user.id)
// Get old password, new password, and confirm new password from req.body
const { oldPassword, newPassword } = req.body
// Validate old password
const isPasswordMatch = await bcrypt.compare(
oldPassword,
userDetails.password
)
if (!isPasswordMatch) {
// If old password does not match, return a 401 (Unauthorized) error
return res
.status(401)
.json({ success: false, message: "The password is incorrect" })
}
// Update password
const encryptedPassword = await bcrypt.hash(newPassword, 10)
const updatedUserDetails = await User.findByIdAndUpdate(
req.user.id,
{ password: encryptedPassword },
{ new: true }
)
// Send notification email
try {
const emailResponse = await mailSender(
updatedUserDetails.email,
"Password for your account has been updated",
passwordUpdated(
updatedUserDetails.email,
`Password updated successfully for ${updatedUserDetails.firstName} ${updatedUserDetails.lastName}`
)
)
console.log("Email sent successfully:", emailResponse.response)
} catch (error) {
// If there's an error sending the email, log the error and return a 500 (Internal Server Error) error
console.error("Error occurred while sending email:", error)
return res.status(500).json({
success: false,
message: "Error occurred while sending email",
error: error.message,
})
}
// Return success response
return res
.status(200)
.json({ success: true, message: "Password updated successfully" })
} catch (error) {
// If there's an error updating the password, log the error and return a 500 (Internal Server Error) error
console.error("Error occurred while updating password:", error)
return res.status(500).json({
success: false,
message: "Error occurred while updating password",
error: error.message,
})
}
}