PermissionsController.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. const { ForbiddenError } = require('../Errors/Errors')
  2. const { hasPermission } = require('./PermissionsManager')
  3. const ManagedUsersHandler = require('../Subscription/ManagedUsersHandler')
  4. /**
  5. * Function that returns middleware to check if the user has permission to access a resource.
  6. * @param {[string]} requiredCapabilities - the capabilities required to access the resource.
  7. * @returns {Function} The middleware function that checks if the user has the required capabilities.
  8. */
  9. function requirePermission(...requiredCapabilities) {
  10. if (
  11. requiredCapabilities.length === 0 ||
  12. requiredCapabilities.some(capability => typeof capability !== 'string')
  13. ) {
  14. throw new Error('invalid required capabilities')
  15. }
  16. const doRequest = async function (req, res, next) {
  17. if (!req.user) {
  18. return next(new Error('no user'))
  19. }
  20. try {
  21. // get the group policy applying to the user
  22. const groupPolicy =
  23. await ManagedUsersHandler.promises.getGroupPolicyForUser(req.user)
  24. // if there is no group policy, the user is not managed
  25. if (!groupPolicy) {
  26. return next()
  27. }
  28. // check that the user has all the required capabilities
  29. for (const requiredCapability of requiredCapabilities) {
  30. // if the user has the permission, continue
  31. if (!hasPermission(groupPolicy, requiredCapability)) {
  32. throw new ForbiddenError(
  33. `user does not have permission for ${requiredCapability}`
  34. )
  35. }
  36. }
  37. next()
  38. } catch (error) {
  39. next(error)
  40. }
  41. }
  42. return doRequest
  43. }
  44. module.exports = {
  45. requirePermission,
  46. }