UNPKG

1.8 kBJavaScriptView Raw
1/**
2 * @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
3 */
4'use strict';
5
6const Base = require('../base/Component');
7
8module.exports = class AccessRule extends Base {
9
10 constructor (config) {
11 super({
12 allow: true, // allow or deny rule result
13 // actions: ['update'],
14 // controllers: ['article'],
15 // permissions: ['?', '@', 'reader'],
16 // methods: ['GET', 'POST'],
17 // deny: fn(action, user)
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; // skip rule
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;
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