PermissionsController.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const { ForbiddenError } = require('../Errors/Errors')
  2. const { hasPermission, getUserCapabilities } = require('./PermissionsManager')
  3. const ManagedUsersHandler = require('../Subscription/ManagedUsersHandler')
  4. /**
  5. * Function that returns middleware to add an `assertPermission` function to the request object to check if the user has a specific capability.
  6. * @returns {Function} The middleware function that adds the `assertPermission` function to the request object.
  7. */
  8. function useCapabilities() {
  9. return async function (req, res, next) {
  10. if (!req.user) {
  11. return next()
  12. }
  13. try {
  14. // get the group policy applying to the user
  15. const groupPolicy =
  16. await ManagedUsersHandler.promises.getGroupPolicyForUser(req.user)
  17. const capabilitySet = getUserCapabilities(groupPolicy)
  18. req.assertPermission = capability => {
  19. if (!capabilitySet.has(capability)) {
  20. throw new ForbiddenError(
  21. `user does not have permission for ${capability}`
  22. )
  23. }
  24. }
  25. next()
  26. } catch (error) {
  27. next(error)
  28. }
  29. }
  30. }
  31. /**
  32. * Function that returns middleware to check if the user has permission to access a resource.
  33. * @param {[string]} requiredCapabilities - the capabilities required to access the resource.
  34. * @returns {Function} The middleware function that checks if the user has the required capabilities.
  35. */
  36. function requirePermission(...requiredCapabilities) {
  37. if (
  38. requiredCapabilities.length === 0 ||
  39. requiredCapabilities.some(capability => typeof capability !== 'string')
  40. ) {
  41. throw new Error('invalid required capabilities')
  42. }
  43. const doRequest = async function (req, res, next) {
  44. if (!req.user) {
  45. return next(new Error('no user'))
  46. }
  47. try {
  48. // get the group policy applying to the user
  49. const groupPolicy =
  50. await ManagedUsersHandler.promises.getGroupPolicyForUser(req.user)
  51. // if there is no group policy, the user is not managed
  52. if (!groupPolicy) {
  53. return next()
  54. }
  55. // check that the user has all the required capabilities
  56. for (const requiredCapability of requiredCapabilities) {
  57. // if the user has the permission, continue
  58. if (!hasPermission(groupPolicy, requiredCapability)) {
  59. throw new ForbiddenError(
  60. `user does not have permission for ${requiredCapability}`
  61. )
  62. }
  63. }
  64. next()
  65. } catch (error) {
  66. next(error)
  67. }
  68. }
  69. return doRequest
  70. }
  71. module.exports = {
  72. requirePermission,
  73. useCapabilities,
  74. }