-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
45 lines (40 loc) · 1.21 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
const jwt = require('jsonwebtoken');
module.exports = function restricted(config, allow) {
// make sure `allow` is an array
const allowArr = Array.isArray(allow) ? allow : [allow];
/**
* reqProp = REQUIRED
* childProp = OPTIONAL
* identifier = REQUIRED
* jwtKey = REQUIRED
* */
const { reqProp, childProp, identifier, jwtKey } = config;
return function(req, res, next) {
// where to find the identifier
const idRequestingResources = childProp
? req[reqProp][childProp]
: req[reqProp];
if (idRequestingResources) {
jwt.verify(idRequestingResources, jwtKey, (err, decoded) => {
if (err) {
console.error(err);
res.status(401).json({ err: err.message });
} else {
req.decodedPayload = decoded;
if (allowArr.length === 0) {
next();
} else {
const isValid = allowArr.includes(decoded[identifier]);
if (isValid) {
next();
} else {
res.status(401).json({ err: 'Access to this route denied' });
}
}
}
});
} else {
res.status(422).json({ err: 'Need to provide reqProp and childProp' });
}
};
};