1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | const Base = require('../base/Component');
|
7 |
|
8 | module.exports = class AccessRule extends Base {
|
9 |
|
10 | constructor (config) {
|
11 | super({
|
12 | allow: true,
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | ...config
|
19 | });
|
20 | }
|
21 |
|
22 | async can (action) {
|
23 | if ((this.actions && !this.actions.includes(action.name))
|
24 | || (this.methods && !this.methods.includes(action.controller.req.method))
|
25 | || (this.controllers && !this.controllers.includes(action.controller.getBaseName()))) {
|
26 | return;
|
27 | }
|
28 | const access = await this.match(action);
|
29 | if (access === true) {
|
30 | return this.allow;
|
31 | }
|
32 | if (access === false) {
|
33 | return !this.allow;
|
34 | }
|
35 | }
|
36 |
|
37 | async match (action) {
|
38 | if (!Array.isArray(this.permissions)) {
|
39 | return true;
|
40 | }
|
41 | const permissions = [];
|
42 | const user = action.user;
|
43 | for (const item of this.permissions) {
|
44 | if (item === '?') {
|
45 | return user.isGuest();
|
46 | }
|
47 | if (item === '@') {
|
48 | return !user.isGuest();
|
49 | }
|
50 | permissions.push(item);
|
51 | }
|
52 | const params = {
|
53 | controller: action.controller
|
54 | };
|
55 | for (const item of permissions) {
|
56 | if (await user.can(item, params)) {
|
57 | return true;
|
58 | }
|
59 | }
|
60 | return false;
|
61 | }
|
62 | }; |
\ | No newline at end of file |