-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.js
90 lines (77 loc) · 1.85 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import jwt from 'jsonwebtoken';
import _ from 'lodash';
import bcrypt from 'bcrypt';
export const createTokens = async (user, secret, secret2) => {
const createToken = jwt.sign(
{
user: _.pick(user, ['id', 'username']),
},
secret,
{
expiresIn: '1h',
},
);
const createRefreshToken = jwt.sign(
{
user: _.pick(user, 'id'),
},
secret2,
{
expiresIn: '7d',
},
);
return [createToken, createRefreshToken];
};
export const refreshTokens = async (token, refreshToken, models, SECRET, SECRET2) => {
let userId = 0;
try {
const { user: { id } } = jwt.decode(refreshToken);
userId = id;
} catch (err) {
return {};
}
if (!userId) {
return {};
}
const user = await models.User.findOne({ where: { id: userId }, raw: true });
if (!user) {
return {};
}
const refreshSecret = user.password + SECRET2;
try {
jwt.verify(refreshToken, user.password + SECRET2);
} catch (err) {
return {};
}
const [newToken, newRefreshToken] = await createTokens(user, SECRET, refreshSecret);
return {
token: newToken,
refreshToken: newRefreshToken,
user,
};
};
export const tryLogin = async (email, password, models, SECRET, SECRET2) => {
const user = await models.User.findOne({ where: { email }, raw: true });
if (!user) {
// user with provided email not found
return {
ok: false,
errors: [{ path: 'email', message: 'Wrong email' }],
};
}
const valid = await bcrypt.compare(password, user.password);
if (!valid) {
// bad password
return {
ok: false,
errors: [{ path: 'password', message: 'Wrong password' }],
};
}
const refreshTokenSecret = user.password + SECRET2;
const [token, refreshToken] = await createTokens(user, SECRET, refreshTokenSecret);
return {
ok: true,
token,
refreshToken,
};
};