generated from Codaisseur/express-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
71 lines (57 loc) · 1.95 KB
/
auth.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
const bcrypt = require("bcrypt");
const { Router } = require("express");
const { toJWT } = require("../auth/jwt");
const User = require("../models/").user;
const { SALT_ROUNDS } = require("../config/constants");
const router = new Router();
router.post("/login", async (req, res, next) => {
try {
const { email, password } = req.body;
if (!email || !password) {
return res
.status(400)
.send({ message: "Please provide both email and password" });
}
const user = await User.findOne({ where: { email } });
if (!user) {
return res.status(400).send({
message: "User with that email not found",
});
}
if (!bcrypt.compareSync(password, user.password)) {
return res.status(400).send({
message: "Password incorrect!",
});
}
delete user.dataValues["password"]; // don't send back the password hash
const token = toJWT({ userId: user.id });
return res.status(200).send({ token, ...user.dataValues });
} catch (error) {
console.log(error);
return res.status(400).send({ message: "Something went wrong, sorry" });
}
});
router.post("/register", async (req, res) => {
const { email, password, name } = req.body;
if (!email || !password || !name) {
return res.status(400).send("Please provide an email, password and a name");
}
try {
const newUser = await User.create({
email,
password: bcrypt.hashSync(password, SALT_ROUNDS),
name,
});
delete newUser.dataValues["password"]; // don't send back the password hash
const token = toJWT({ userId: newUser.id });
res.status(201).json({ token, ...newUser.dataValues });
} catch (error) {
if (error.name === "SequelizeUniqueConstraintError") {
return res
.status(400)
.send({ message: "There is an existing account with this email" });
}
return res.status(400).send({ message: "Something went wrong, sorry" });
}
});
module.exports = router;