-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauth.js
More file actions
61 lines (49 loc) · 1.54 KB
/
auth.js
File metadata and controls
61 lines (49 loc) · 1.54 KB
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
const jwt = require("jsonwebtoken");
const { jwtConfig } = require("./config");
const db = require("./db/models");
const bearerToken = require("express-bearer-token");
const { secret, expiresIn } = jwtConfig;
const getUserToken = (user) => {
// Don't store the user's hashed password
// in the token data.
const userDataForToken = {
id: user.id,
userName: user.userName,
};
// Create the token.
const token = jwt.sign(
{ data: userDataForToken },
secret,
{ expiresIn: parseInt(expiresIn, 10) } // 604,800 seconds = 1 week
);
return token;
};
const restoreUser = (req, res, next) => {
// token being parsed from request header by the bearerToken middleware
// function in app.js:
const { token } = req;
// console.log(req.token);
if (!token) {
return next();
}
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 db.User.findByPk(id);
} catch (e) {
return next(e);
}
if (!req.user) {
// Send a "401 Unauthorized" response status code
// along with an "WWW-Authenticate" header value of "Bearer".
return res.set("WWW-Authenticate", "Bearer").status(401).end();
}
return next();
});
};
const requireAuth = [bearerToken(), restoreUser];
module.exports = { getUserToken, requireAuth };