-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathpermissions.js
41 lines (37 loc) · 1.31 KB
/
permissions.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
const util = require('../util')
let authenticatedRoleExists
async function addRolePermissions (req, roles) {
const rolePermissions = await util.getEffectivePermissionsForRoles(roles, req.db)
req.permissions ??= {}
req.permissions = { ...req.permissions, ...rolePermissions }
}
async function doesAuthenticatedRoleExist(req) {
if (typeof authenticatedRoleExists === 'undefined') {
try {
await req.db.role.get('Authenticated')
authenticatedRoleExists = true
} catch (e) {
authenticatedRoleExists = false
}
}
return authenticatedRoleExists
}
module.exports.addRolePermissionsAsync = async function addRolePermissionsMiddlewareAsync(req) {
if (!req.settings || !req.settings.enforce_permissions) {
// Use a dummy permission getter
req.hasPermission = () => true
return
}
req.hasPermission = (permission) => util.hasPermission(req.permissions, permission)
let roles = ['Anonymous']
const isAuthenticatedRole = await doesAuthenticatedRoleExist(req)
if (req.uid) {
roles = (req.user.roles || []).concat(isAuthenticatedRole ? ['Authenticated'] : [])
} else {
req.user = {}
}
await addRolePermissions(req, roles)
}
module.exports.middleware = function addRolePermissionsMiddleware (req, res, next) {
module.exports.addRolePermissionsAsync(req).then(next).catch(next)
}