-
Notifications
You must be signed in to change notification settings - Fork 274
/
Copy pathauth.controller.js
88 lines (73 loc) · 2.45 KB
/
auth.controller.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
import bcrypt from "bcryptjs";
import User from "../models/user.model.js";
import generateTokenAndSetCookie from "../utils/generateToken.js";
export const signup = async (req, res) => {
try {
const { fullName, username, password, confirmPassword, gender } = req.body;
if (password !== confirmPassword) {
return res.status(400).json({ error: "Passwords don't match" });
}
const user = await User.findOne({ username });
if (user) {
return res.status(400).json({ error: "Username already exists" });
}
// HASH PASSWORD HERE
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);
// https://avatar-placeholder.iran.liara.run/
const boyProfilePic = `https://avatar.iran.liara.run/public/boy?username=${username}`;
const girlProfilePic = `https://avatar.iran.liara.run/public/girl?username=${username}`;
const newUser = new User({
fullName,
username,
password: hashedPassword,
gender,
profilePic: gender === "male" ? boyProfilePic : girlProfilePic,
});
if (newUser) {
// Generate JWT token here
generateTokenAndSetCookie(newUser._id, res);
await newUser.save();
res.status(201).json({
_id: newUser._id,
fullName: newUser.fullName,
username: newUser.username,
profilePic: newUser.profilePic,
});
} else {
res.status(400).json({ error: "Invalid user data" });
}
} catch (error) {
console.log("Error in signup controller", error.message);
res.status(500).json({ error: "Internal Server Error" });
}
};
export const login = async (req, res) => {
try {
const { username, password } = req.body;
const user = await User.findOne({ username });
const isPasswordCorrect = await bcrypt.compare(password, user?.password || "");
if (!user || !isPasswordCorrect) {
return res.status(400).json({ error: "Invalid username or password" });
}
generateTokenAndSetCookie(user._id, res);
res.status(200).json({
_id: user._id,
fullName: user.fullName,
username: user.username,
profilePic: user.profilePic,
});
} catch (error) {
console.log("Error in login controller", error.message);
res.status(500).json({ error: "Internal Server Error" });
}
};
export const logout = (req, res) => {
try {
res.cookie("jwt", "", { maxAge: 0 });
res.status(200).json({ message: "Logged out successfully" });
} catch (error) {
console.log("Error in logout controller", error.message);
res.status(500).json({ error: "Internal Server Error" });
}
};