-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathguard.js
45 lines (34 loc) · 1.16 KB
/
guard.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 routeGuard = (accessMatrix) => {
return (req, res, next) => {
if (!req.authInfo.hasOwnProperty('roles')) {
return res.status(403).json({ error: 'No roles claim found!' });
}
const roles = req.authInfo['roles'];
if (!requestHasRequiredAttributes(accessMatrix, req.path, req.method, roles)) {
return res.status(403).json({ error: 'User does not have the role, method or path' });
}
next();
};
};
/**
* This method checks if the request has the correct roles, paths and methods
* @param {Object} accessMatrix
* @param {String} path
* @param {String} method
* @param {Array} roles
* @returns boolean
*/
const requestHasRequiredAttributes = (accessMatrix, path, method, roles) => {
const accessRules = Object.values(accessMatrix);
const accessRule = accessRules
.find((accessRule) => path.includes(accessRule.path));
if (accessRule.methods.includes(method)) {
const hasRole = accessRule.roles
.some((role) => roles.includes(role));
if (hasRole) {
return true
}
}
return false;
};
module.exports = routeGuard;