UNPKG

2.26 kBJavaScriptView Raw
1'use strict';
2var u = require('./util')
3
4var isArray = Array.isArray
5
6function isFunction (f) {
7 return 'function' === typeof f
8}
9
10function join (str) {
11 return Array.isArray(str) ? str.join('.') : str
12}
13
14function toArray(str) {
15 return isArray(str) ? str : str.split('.')
16}
17
18function isPerms (p) {
19 return (
20 p &&
21 isFunction(p.pre) &&
22 isFunction(p.test) &&
23 isFunction(p.post)
24 )
25}
26
27/*
28
29perms:
30
31a given capability may be permitted to call a particular api.
32but only if a perms function returns true for the arguments
33it passes.
34
35suppose, an app may be given access, but may only create functions
36with it's own properties.
37
38create perms:
39 {
40 allow: ['add', 'query'], deny: [...],
41 rules: {
42 add: {
43 call: function (value) {
44 return (value.type === 'task' || value.type === '_task')
45 },
46 query: {
47 call: function (value) {
48 safe.contains(value, {path: ['content', 'type'], eq: 'task'}) ||
49 safe.contains(value, {path: ['content', 'type'], eq: '_task'})
50 },
51 filter: function (value) {
52 return (value.type === 'task' || value.type === '_task')
53 }
54 }
55 }
56 }
57*/
58
59module.exports = function (opts) {
60 if(isPerms(opts)) return opts
61 if(isFunction(opts)) return {pre: opts}
62 var allow = null
63 var deny = {}
64
65 function perms (opts) {
66 if(opts.allow) {
67 allow = {}
68 opts.allow.forEach(function (path) {
69 u.set(allow, toArray(path), true)
70 })
71 }
72 else allow = null
73
74 if(opts.deny)
75 opts.deny.forEach(function (path) {
76 u.set(deny, toArray(path), true)
77 })
78 else deny = {}
79
80 return this
81 }
82
83 if(opts) perms(opts)
84
85 perms.pre = function (name, args) {
86 name = isArray(name) ? name : [name]
87 if(allow && !u.prefix(allow, name))
88 return new Error('method:'+name + ' is not in list of allowed methods')
89
90 if(deny && u.prefix(deny, name))
91 return new Error('method:'+name + ' is on list of disallowed methods')
92 }
93
94 perms.post = function (err, value) {
95 //TODO
96 }
97
98 //alias for pre, used in tests.
99 perms.test = function (name, args) {
100 return perms.pre(name, args)
101 }
102
103 perms.get = function () {
104 return {allow: allow, deny: deny}
105 }
106
107 return perms
108}
109
110