-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
55 lines (44 loc) · 1.11 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
const bearerToken = require('express-bearer-token');
const jwt = require('jsonwebtoken');
const { User } = require('./db/models');
const { jwtConfig: { secret, expiresIn } } = require('./config');
const generateToken = (id, username) => {
const data = { id, username };
return {
token: jwt.sign(
{ data },
secret,
{ expiresIn: +expiresIn }
)
}
};
const restoreUser = (req, res, next) => {
const { token } = req;
if (!token) {
const err = new Error('There\'s no token attached with the request.');
err.status = 401;
return next(err);
}
jwt.verify(token, secret, null, async (err, payload) => {
if (err) {
err.status = 403;
return next(err);
}
try {
res.locals.user = await User.findByPk(payload.data.id);
} catch(e) {
return next(e);
}
if (!res.locals.user) {
const err = new Error('User not found with the given token.');
err.status = 404;
return next(err);
}
next();
})
};
const checkIfAuthenticated = [bearerToken(), restoreUser];
module.exports = {
generateToken,
checkIfAuthenticated
}