const { Middleware } = require('libflitter') class PermissionMiddleware extends Middleware { static get services() { return [...super.services, 'models'] } async test(req, res, next, { check }) { const Policy = this.models.get('iam:Policy') // If the request was authorized using an OAuth2 bearer token, // make sure the associated client has permission to access this endpoint. if ( req?.oauth?.client ) { if ( !req.oauth.client.can(check) ) return res.status(401) .message('Insufficient permissions (OAuth2 Client).') .api() } const policy_denied = await Policy.check_user_denied(req.user, check) const policy_access = await Policy.check_user_access(req.user, check) // Make sure the user has permission if ( policy_denied || (!req.user.can(check) && !policy_access) ) return res.status(401) .message('Insufficient permissions.') .api() return next() } } module.exports = exports = PermissionMiddleware