-
Notifications
You must be signed in to change notification settings - Fork 9.7k
/
Copy pathAuthController.js
89 lines (79 loc) · 2.41 KB
/
AuthController.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
const UserModel = require("../Models/User");
const bcrypt = require('bcryptjs');
const jwt=require('jsonwebtoken');
const signup = async (req, res) => {
try {
const { name, email, password } = req.body;
// Check if the user already exists
const user = await UserModel.findOne({ email });
if (user) {
return res.status(409).json({
message: "User already exists, you can login",
success: false
});
}
// Hash the password
const hashedPassword = await bcrypt.hash(password, 10);
// Create a new user instance with hashed password
const userModel = new UserModel({
name,
email,
password: hashedPassword // Set the hashed password here
});
// Save the new user to the database
await userModel.save();
res.status(201).json({
message: "Signup successful",
success: true
});
} catch (err) {
// Log the error for debugging
console.error("Error during signup:", err);
res.status(500).json({
message: "Internal server error",
success: false
});
}
}
const login = async (req, res) => {
try {
const { email, password } = req.body;
// Check if the user already exists
const user = await UserModel.findOne({ email });
const errorMsg='Auth failed email or password is wrong';
if (!user) {
return res.status(403).json({
message: errorMsg,
success: false
});
}
const isPassEqual=await bcrypt.compare(password,user.password);
if(!isPassEqual){
return res.status(403)
.json({message:errorMsg,success:false});
}
const jwtToken=jwt.sign(
{email:user.email,_id:user._id},
process.env.JWT_SECRET,
{expiresIn:'24h'}
)
res.status(200).json({
message: "Login successful",
success: true,
jwtToken,
email,
name:user.name
});
} catch (err) {
// Log the error for debugging
console.error("Error during signup:", err);
res.status(500).json({
message: "Internal server error",
success: false
});
}
}
module.exports = {
signup,
login
};