-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
59 lines (48 loc) · 1.56 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
const unless = require('koa-unless');
const normalizeAcl = acl => acl.map((rule) => {
if (!rule.action) throw new TypeError('action must be set in ACL rule');
return {
path: rule.path ? new RegExp(rule.path.toLowerCase()) : undefined,
role: rule.role,
methods: rule.methods ? rule.methods.map(value => value.toLowerCase()) : undefined,
action: rule.action,
match(path, method, roleNames) {
if (this.path) {
if (!this.path.test(path)) return false;
}
if (this.methods &&
!this.methods.includes(method)) {
return false;
}
if (this.role) {
for (let i = 0; i < roleNames.length; i += 1) {
if (roleNames.includes(this.role)) return true;
}
return false;
}
return true;
}
};
});
module.exports = (opts) => {
const { getRoles, acl } = opts;
if (typeof getRoles !== 'function') throw new TypeError('getRoles must be a function');
if (!acl || !Array.isArray(acl)) throw new TypeError('acl must be an nonempty array');
const realAcl = normalizeAcl(acl);
const middleware = (ctx, next) => {
const { path, method } = ctx;
const roleNames = getRoles(ctx);
if (roleNames.includes('admin')) return next();
for (let i = 0; i < realAcl.length; i += 1) {
const rule = realAcl[i];
if (rule.match(path.toLowerCase(), method.toLowerCase(), roleNames)) {
if (rule.action === 'accept') return next();
break;
}
}
ctx.throw(403);
return false;
};
middleware.unless = unless;
return middleware;
};