-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
70 lines (61 loc) · 1.53 KB
/
index.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
59
60
61
62
63
64
65
66
67
68
69
70
const jwt = require('jsonwebtoken');
const fs = require('fs');
let secretOrCert, options = null;
/**
* Express middleware function
* @param {object} req
* @param {object} res
* @param {function} next
*/
const middlewareFunc = (req, res, next) => {
const token = clearToken(req.headers.authorization);
jwt.verify(token, secretOrCert, options, (err, decoded) => {
if (err) {
res.status(403).json(isEmpty(err) ? { message: 'Wrong token!' } : err);
} else {
req.tokenData = decoded;
next();
}
});
};
/**
* Remove unrelated string in token like Bearer.
* @param {string} token
*/
const clearToken = (token) => {
if (/\s/g.test(token)) {
return token.split(' ')[1];
} else {
return token;
}
};
/**
* Read cert file from a path.
* @param {string} path
*/
const bufferCert = (path) => {
try {
return fs.readFileSync(path);
} catch (error) {
throw new Error('Public Certificate file is missing!');
}
};
module.exports = (opt) => {
if (!opt) {
throw new Error('Please provide secret for jwt middleware at least!');
}
secretOrCert = (typeof opt === "string")
? opt
: opt.hasOwnProperty('secret')
? opt.secret
: bufferCert(opt.cert);
options = opt;
return middlewareFunc;
};
/**
* Check if object is empty
* @param {object} obj
*/
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}