-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
103 lines (84 loc) · 1.89 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
91
92
93
94
95
96
97
98
99
100
101
102
import jwt from 'jsonwebtoken';
import pick from 'lodash/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 (error) {
return {};
}
if (!userId) {
return {};
}
// raw to not get sequelize obj
const user = await models.User.findOne({ where: { id: userId }, raw: true });
if (!user) {
return {};
}
const refreshSecret = user.password + SECRET2;
try {
jwt.verify(refreshToken, refreshSecret);
} catch (error) {
return {};
}
const [newToken, newRefreshToken] = await createTokens(user, SECRET, refreshSecret);
return {
token: newToken,
refreshToken: newRefreshToken,
};
};
export const tryLogin = async (email, password, models, SECRET, SECRET2) => {
const user = await models.User.findOne({
where: { email },
raw: true,
});
if (!user) {
return {
ok: false,
errors: [{ path: 'email', message: 'No user with this email exists' }],
};
}
const valid = await bcrypt.compare(password, user.password);
if (!valid) {
return {
ok: false,
errors: [{ path: 'password', message: 'Wrong email or password' }],
};
}
const refreshTokenSecret = `${user.password}${SECRET2}`;
const [
token,
refreshToken,
] = await createTokens(user, SECRET, refreshTokenSecret);
return {
ok: true,
token,
refreshToken,
};
};