-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
58 lines (48 loc) · 1.32 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
const jwt = require('jsonwebtoken');
const {jwtConfig} = require("./config");
const {secret, expiresIn} = jwtConfig;
const bearerToken = require('express-bearer-token');
const {User} = require('./db/models');
const getUserToken = (user) =>{
console.log()
const userDataForToken = {
id: user.id,
email: user.email
}
const token = jwt.sign(
{data: userDataForToken},
secret,
{ expiresIn: parseInt(expiresIn, 10)}
)
return token;
}
const restoreUser = (req, res, next) => {
const {
token
} = req;
if (!token) {
console.log("token not found");
return res.set("WWW-Authenticate", "Bearer").status(401).end();
}
return jwt.verify(token, secret, null, async (err, jwtPayload) => {
if (err) {
console.log("this is the error: ",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};