-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathacl.js
More file actions
54 lines (51 loc) · 1.92 KB
/
acl.js
File metadata and controls
54 lines (51 loc) · 1.92 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
module.exports = ({ apiPath, rules }) => {
// Check if the last character is a slash
// otherwise add a slash at the end
apiPath += apiPath.slice(-1) !== "/" ? "/" : "";
return function(req, res, next) {
if (req.url.indexOf(apiPath) === 0) {
// This is an api route.
// Get the users role and the entity requested
// (if not logged in set the role visitor)
let userRole = req.session.user ?
req.session.user.role || "user" :
"user";
let url = req.url;
let method = req.method.toLowerCase();
url += url.slice(-1) !== "/" ? "/" : "";
let entity = url
.split(apiPath)
.join("")
.split("/")[0];
// Loop through our rules
for (let rule in rules) {
if (rule === entity) {
// Found the rule
// loop through roles
for (let role in rules[rule]) {
if (userRole === role) {
// Found the role
// now get allowed methods
let allowed = rules[rule][role]
.toLowerCase()
.split(" ");
if (
allowed.includes(method) ||
allowed.includes("all")
) {
// allow user to see this routes
next();
return;
}
}
}
}
}
// Do not allow...
// (don't say forbidden it encourages hackers)
res.send("Page not found.");
return;
}
next();
};
};