-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
118 lines (103 loc) · 2.55 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import jwt from 'jsonwebtoken';
import _ from 'lodash';
import bcrypt from 'bcrypt';
/**
* Creates the auth tokens.
*
* @param {String} user The user.
* @param {String} secret1 The secret.
* @param {String} secret2 The secret 2.
*/
export const createTokens = async (user, secret1, secret2) => {
const createToken = jwt.sign(
{
user: _.pick(user, ['id', 'username']),
},
secret1,
{
expiresIn: '1h',
},
);
const createRefreshToken = jwt.sign(
{
user: _.pick(user, ['id', 'username']),
},
secret2,
{
expiresIn: '7d',
},
);
return [createToken, createRefreshToken];
};
/**
* Refreshes a users auth tokens.
*
* @param {String} token The token.
* @param {String} refreshToken The refresh token.
* @param {Object} models The models.
* @param {String} SECRET1 The secret.
*/
export const refreshTokens = async (token, refreshToken, models, SECRET1) => {
let userId = -1;
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 {};
}
try {
jwt.verify(refreshToken, user.refreshSecret);
} catch (err) {
return {};
}
const [newToken, newRefreshToken] = await createTokens(user, SECRET1, user.refreshSecret);
return {
token: newToken,
refreshToken: newRefreshToken,
user,
};
};
/**
* Logs a user in.
*
* @param {String} email The email.
* @param {String} password The password.
* @param {Object} models The models.
* @param {String} SECRET1 The secret.
* @param {String} SECRET2 The secret 2.
*/
export const tryLogin = async (email, password, models, SECRET1, SECRET2) => {
const user = await models.User.findOne({ where: { email }, raw: true });
if (!user) {
// user with provided email not found
return {
ok: false,
errors: [{ path: '', message: 'Invalid email or password.' }],
};
}
const valid = await bcrypt.compare(password, user.password);
if (!valid) {
// bad password
return {
ok: false,
errors: [{ path: '', message: 'Invalid email or password.' }],
};
}
const refreshTokenSecret = user.password + SECRET2;
const [token, refreshToken] = await createTokens(user, SECRET1, refreshTokenSecret);
return {
userInfo: user,
ok: true,
token,
refreshToken,
};
};