-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathauth.js
71 lines (63 loc) · 1.66 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 { encrypt, compare } = require("../utils/handleJwt");
const {
handleHttpError,
handleErrorResponse,
} = require("../utils/handleError");
const { tokenSign } = require("../utils/handleToken");
const { userModel } = require("../models");
const { matchedData } = require("express-validator");
/**
* Controller for login
* @param {*} req
* @param {*} res
* @returns
*/
const loginCtrl = async (req, res) => {
try {
const body = matchedData(req);
const user = await userModel.findOne({ email: body.email });
if (!user) {
handleErrorResponse(res, "USER_NOT_EXISTS", 404);
return;
}
const checkPassword = await compare(body.password, user.password);
if (!checkPassword) {
handleErrorResponse(res, "PASSWORD_INVALID", 402);
return;
}
const tokenJwt = await tokenSign(user);
const data = {
token: tokenJwt,
user: user,
};
res.send({ data });
} catch (e) {
handleHttpError(res, e);
}
};
/**
* Controller for register
* @param {*} req
* @param {*} res
* @returns
*/
const registerCtrl = async (req, res) => {
try {
const body = matchedData(req);
// const checkIsExist = await userModel.findOne({
// where: { email: body.email },
// });
const checkIsExist = await userModel.findOne({ email: body.email });
if (checkIsExist) {
handleErrorResponse(res, "USER_EXISTS", 401);
return;
}
const password = await encrypt(body.password);
const bodyInsert = { ...body, password };
const data = await userModel.create(bodyInsert);
res.send({ data });
} catch (e) {
handleHttpError(res, e);
}
};
module.exports = { loginCtrl, registerCtrl };