blob: 94dfa857e68e60a8d7a3af71e2340aec235b45fc (
plain)
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
|
const db = require('./db');
const userHasPermission = async (user, permission_name) => {
const permission = await db('permissions').where({ name: permission_name }).first();
const userPermission = await db('users_permissions')
.where({ user_id: user.id, permission_id: permission.id })
.first();
return !!userPermission;
};
const userHasPermissions = async (user, permission_names) => {
for (permission_name of permission_names) {
const hasPermission = await userHasPermission(user, permission_name);
if (!hasPermission) {
return false;
}
}
return true;
};
const permissionMiddleware = permission_name => async (req, res, next) => {
const user = req.user;
const hasPermission = Array.isArray(permission_name)
? await userHasPermissions(user, permission_name)
: await userHasPermission(user, permission_name);
if (hasPermission) {
await next();
} else {
res.status(401);
res.json({
error: 'Required permission missing.',
permission_name,
});
}
};
module.exports = {
userHasPermission,
permissionMiddleware,
};
|