feat(xo-acl-resolver/assert): throw error if unauthorized

This commit is contained in:
Julien Fontanet
2018-11-13 10:46:38 +01:00
committed by Pierre Donias
parent df44487363
commit ca7d520997
5 changed files with 32 additions and 8 deletions
+25 -5
View File
@@ -1,5 +1,9 @@
'use strict'
const { unauthorized } = require('xo-common/api-errors')
// ===================================================================
// These global variables are not a problem because the algorithm is
// synchronous.
let permissionsByObject
@@ -105,23 +109,26 @@ function checkAuthorization (objectId, permission) {
// -------------------------------------------------------------------
module.exports = (
function assertPermissions (
permissionsByObject_,
getObject_,
permissions,
permission
) => {
) {
// Assign global variables.
permissionsByObject = permissionsByObject_
getObject = getObject_
try {
if (permission) {
return checkAuthorization(permissions, permission)
if (permission !== undefined) {
const objectId = permissions
if (!checkAuthorization(objectId, permission)) {
throw unauthorized(permission, objectId)
}
} else {
for (const [objectId, permission] of permissions) {
if (!checkAuthorization(objectId, permission)) {
return false
throw unauthorized(permission, objectId)
}
}
}
@@ -132,3 +139,16 @@ module.exports = (
permissionsByObject = getObject = null
}
}
exports.assert = assertPermissions
exports.check = function checkPermissions () {
try {
assertPermissions.apply(undefined, arguments)
return true
} catch (error) {
if (unauthorized.is(error)) {
return false
}
throw error
}
}
+3
View File
@@ -21,5 +21,8 @@
],
"engines": {
"node": ">=6"
},
"dependencies": {
"xo-common": "^0.1.2"
}
}