-
-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathauth.middleware.js
More file actions
52 lines (46 loc) · 1.19 KB
/
auth.middleware.js
File metadata and controls
52 lines (46 loc) · 1.19 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
const jwt = require('jsonwebtoken');
const { CONFIG_AUTH } = require('../config');
function verifyToken(req, res, next) {
// Allow users to set token
// eslint-disable-next-line dot-notation
let token = req.headers['x-access-token'] || req.headers['authorization'];
if (token.startsWith('Bearer ')) {
// Remove Bearer from string
token = token.slice(7, token.length);
}
if (!token) {
return res.sendStatus(403);
}
try {
const decoded = jwt.verify(token, CONFIG_AUTH.SECRET);
res.cookie('token', token, { httpOnly: true });
req.userId = decoded.id;
return next();
} catch (err) {
return res.sendStatus(401);
}
}
function verifyCookie(req, res, next) {
jwt.verify(req.cookies.token, CONFIG_AUTH.SECRET, (err, decoded) => {
if (err) {
return res.sendStatus(401);
}
req.userId = decoded.id;
req.role = decoded.accessLevel;
next();
});
}
function addCookieIfAvailable(req, res, next) {
jwt.verify(req.cookies.token, CONFIG_AUTH.SECRET, (err, decoded) => {
if (!err) {
req.userId = decoded.id;
}
next();
});
}
const AuthUtil = {
verifyToken,
verifyCookie,
addCookieIfAvailable,
};
module.exports = AuthUtil;