-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthController.js
More file actions
73 lines (62 loc) · 1.58 KB
/
Copy pathauthController.js
File metadata and controls
73 lines (62 loc) · 1.58 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
import User from "../models/User.js";
import jwt from "jsonwebtoken";
export const registerUser = async (req, res) => {
try {
const { username, email, password, age } = req.body;
if (!username || !email || !password) {
return res
.status(400)
.json({ message: "Please fill all required fields" });
}
const userExists = await User.findOne({ email });
if (userExists) {
return res.status(400).json({ message: "User already exists" });
}
const user = await User.create({
username,
email,
password,
age: age || null,
});
res.status(201).json({
_id: user._id,
username: user.username,
email: user.email,
role: user.role,
age: user.age,
});
} catch (error) {
console.log(error);
}
};
export const loginUser = async (req, res) => {
try {
const { email, password } = req.body;
if (!email || !password) {
return res
.status(400)
.json({ message: "username and passwored requiered" });
}
const user = await User.findOne({ email });
if (!user || !(await user.matchPassword(password))) {
return res.status(401).json({ message: "Invalid credentials" });
}
const token = jwt.sign(
{
id: user._id,
name: user.username,
admin: user.role == "admin" ? true : false,
},
process.env.JWT_SECRET,
{ expiresIn: "1d" }
);
res.status(200).json({
_id: user._id,
username: user.username,
email,
token,
});
} catch (error) {
console.log(error);
}
};