-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthController.js
More file actions
62 lines (51 loc) · 1.8 KB
/
Copy pathAuthController.js
File metadata and controls
62 lines (51 loc) · 1.8 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
const bcrypt = require('bcryptjs');
const User = require('./User');
const generateToken = require('./generateToken');
const userSchema = require('./Zod');
// signup
const signup = async (req, res) => {
try {
const parsed = userSchema.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ errors: parsed.error.errors });
}
const { email, password } = parsed.data;
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json({ msg: "User already exists" });
}
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({ email, password: hashedPassword });
await newUser.save();
const token = generateToken(newUser._id);
res.status(200).json({ msg: "User created", token });
} catch (err) {
console.error(err);
res.status(500).json({ msg: "Server error", error: err.message });
}
};
// signin
const signin = async (req, res) => {
try {
const parsed = userSchema.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ errors: parsed.error.errors });
}
const { email, password } = parsed.data;
const user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ msg: "Invalid credentials" });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(400).json({ msg: "Invalid credentials" });
}
const token = generateToken(user._id);
// Send token to fe
res.status(200).json({ msg: "Login successful", token });
} catch (err) {
console.error(err);
res.status(500).json({ msg: "Server error", error: err.message });
}
};
module.exports = { signup, signin };