-
-
Notifications
You must be signed in to change notification settings - Fork 365
Expand file tree
/
Copy pathauth.controller.js
More file actions
58 lines (51 loc) · 1.39 KB
/
auth.controller.js
File metadata and controls
58 lines (51 loc) · 1.39 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
import User from "../models/user.model.js";
import createError from "../utils/createError.js";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
export const register = async (req, res, next) => {
try {
const hash = bcrypt.hashSync(req.body.password, 5);
const newUser = new User({
...req.body,
password: hash,
});
await newUser.save();
res.status(201).send("User has been created.");
} catch (err) {
next(err);
}
};
export const login = async (req, res, next) => {
try {
const user = await User.findOne({ username: req.body.username });
if (!user) return next(createError(404, "User not found!"));
const isCorrect = bcrypt.compareSync(req.body.password, user.password);
if (!isCorrect)
return next(createError(400, "Wrong password or username!"));
const token = jwt.sign(
{
id: user._id,
isSeller: user.isSeller,
},
process.env.JWT_KEY
);
const { password, ...info } = user._doc;
res
.cookie("accessToken", token, {
httpOnly: true,
})
.status(200)
.send(info);
} catch (err) {
next(err);
}
};
export const logout = async (req, res) => {
res
.clearCookie("accessToken", {
sameSite: "none",
secure: true,
})
.status(200)
.send("User has been logged out.");
};