-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
94 lines (81 loc) · 1.91 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* @author Axel Boberg <hello@axelboberg.se>
* @copyright Axel Boberg © 2019
*/
const should = require('./lib/should')
class Agent {
constructor (policy, opts) {
this._policy = policy
this._opts = opts
}
/**
* Authorize some input data
*
* @param { Object } input
*//**
* Authorize some input data
*
* @param { Object } input
* @param { Object } opts
*//**
* Authorize some input data
* using a policy
*
* @param { Object } input
* @param { Array<Array<Function>> } policy
*//**
* Authorize some input data
* using a policy
*
* @param { Object } input
* @param { Array<Array<Function>> } policy
* @param { Object } opts
*/
authorize (...args) {
let input,
output = {},
policy = this._policy || [],
opts = this._opts || {}
/*
Extract parameters from arguments
*/
if (args.length === 1) input = args[0]
if (args.length === 2 && Array.isArray(args[1])) [ input, policy ] = args
if (args.length === 2 && !Array.isArray(args[1])) [ input, opts ] = args
if (args.length === 3) [ input, policy, opts ] = args
if (!policy || !Array.isArray(policy)) {
throw new TypeError('Policy must be an array')
}
let grantedBy
for (let block of policy) {
let granted = true
for (let func of block) {
const res = func(input, output)
/*
Break as soon as a policy
has failed to prove true
*/
if (!res) {
granted = false
break
}
}
if (granted) {
grantedBy = block
break
}
}
if (opts.detailedResponse) {
const res = {
granted: !!grantedBy,
output: output
}
if (grantedBy) res.policy = grantedBy
return res
}
return !!grantedBy
}
}
module.exports = Agent
module.exports.Agent = Agent
module.exports.should = should