forked from Greg001100/harmony
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
53 lines (40 loc) · 1.16 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
const jwt = require("jsonwebtoken");
const { User } = require("./models");
const bearerToken = require("express-bearer-token");
const uuid = require('uuid').v4;
const { jwtConfig: { secret, expiresIn } } = require('./config/index');
const getUserToken = (user) => {
const data = {
id: user.id,
email: user.email,
};
const jwtid = uuid();
return {
jti: jwtid,
token: jwt.sign({ data }, secret, { expiresIn: Number.parseInt(expiresIn), jwtid })
};
};
const restoreUser = (req, res, next) => {
const { token } = req;
if (!token) {
return res.set("WWW-Authenticate", "Bearer").status(401).end();
}
return jwt.verify(token, secret, null, async (err, jwtPayload) => {
if (err) {
err.status = 401;
return next(err);
}
const { id } = jwtPayload.data;
try {
req.user = await User.findByPk(id);
} catch (e) {
return next(e);
}
if (!req.user) {
return res.set("WWW-Authenticate", "Bearer").status(401).end();
}
return next();
});
};
const requireAuth = [bearerToken(), restoreUser];
module.exports = { getUserToken, requireAuth };