-
Notifications
You must be signed in to change notification settings - Fork 4
/
check.js
73 lines (67 loc) · 2.24 KB
/
check.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
/**
* Created by keyvan on 11/26/16.
*/
import {parseIds} from './preprocess';
import {fetchOne} from './postprocess';
import {Procedure} from './data';
const checkWith = ({
name = 'checkWith',
condition = (params, ctx) => true,
except = (params, ctx) => false
} = {}) =>
new Procedure({
name: name,
preProcess: [
(params, ctx) => [params, except.apply(null, [params, ctx])],
([params, exception], ctx) => {
if (exception)
params.result = true;
else
params.result = condition.apply(null, [params, ctx]);
return params;
}
]
});
// check Hook
// checkOwner
// params before: {resourceIdParamName} <number> | <string> | <Neo4jInt>
// params after: {resourceIdParamName} <Neo4jInt>
const checkOwner = ({
name = 'checkOwner',
resourceIdParamName = 'id',
pattern = '(user)-[:HAS]->(resource)',
except = (params, ctx) => false
} = {}) =>
new Procedure({
name: name,
preProcess: [
parseIds(resourceIdParamName),
(params, ctx) => [params, except.apply(null, [params, ctx])],
([params, exception], ctx) => {
if (exception)
params.result = true;
else
params.cypher = `MATCH ${pattern} WHERE id(user) = ${ctx.user.id} ` +
`AND id(resource) = {${resourceIdParamName}} ` +
'RETURN count(resource) > 0';
return params;
}
],
postProcess: fetchOne
});
// Use allowedRoles for this functionality
// Made to be used as 'except', e.g.
// checkOwner({ except: userHasAnyOfRoles(['admin', 'reviewer']) })
const userHasAnyOfRoles = roles => (params, ctx) => {
if (!ctx)
throw new Error("'ctx' not passed to procedure");
if (!ctx.user)
throw new Error('user not logged in');
roles = roles.map(role => role.toLowerCase());
for (const role of roles)
if (ctx.user.roles.indexOf(role.toLowerCase()) >= 0)
return true;
return false;
};
const userIs = role => userHasAnyOfRoles([role]);
export {checkWith, checkOwner, userHasAnyOfRoles, userIs};