This repository was archived by the owner on Jun 27, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathrestrictToOwnerOrModerator.js
More file actions
64 lines (55 loc) · 2.03 KB
/
restrictToOwnerOrModerator.js
File metadata and controls
64 lines (55 loc) · 2.03 KB
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
const { getByDot } = require('feathers-hooks-common');
const errors = require('@feathersjs/errors');
module.exports = function restrictToOwnerOrModerator (query = {}) { // eslint-disable-line no-unused-vars
return function (hook) {
if (hook.type !== 'before') {
throw new Error('The "restrictToOwnerOrModerator" hook should only be used as a "before" hook.');
}
const isFindOrGet = ['find', 'get'].includes(hook.method);
if (!isFindOrGet && !getByDot(hook, 'params.before')) {
throw new Error('The "restrictToOwnerOrModerator" hook should be used after the "stashBefore()" hook');
}
if (!hook.params || !hook.params.user) {
return false;
}
const role = getByDot(hook, 'params.user.role');
const isModOrAdmin = role && ['admin', 'moderator'].includes(role);
// allow for mods or admins
if (isModOrAdmin) {
return hook;
}
const userId = getByDot(hook, 'params.user._id');
const users = getByDot(hook, 'params.before.users');
const isOwner = userId && users &&
users.some(({id}) => id === userId.toString());
// change the query if the method is find or get
if (isFindOrGet) {
// restrict to owner or given query
const restrictedQuery = {
$or: [
{ 'users.id': userId },
{ ...query }
]
};
hook.params.query = Object.assign(hook.params.query, restrictedQuery);
return hook;
}
let hasError = false;
const keys = Object.keys(query);
if (!isOwner && keys.length) {
keys.forEach((key) => {
if (query[key] !== getByDot(hook, `params.before.${key}`)) {
hasError = true;
}
});
if (hasError) {
// if any of the given query params is not identical with the current values this action is forbidden
throw new errors.Forbidden('You can\'t alter this record!');
}
} else if (!isOwner) {
// his action is forbidden if its not the owner
throw new errors.Forbidden('You can\'t alter this record!');
}
return hook;
};
};