You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
2.4 KiB

11 months ago
  1. const { User } = require("../../../models/user");
  2. const { ROLES } = require("../../middleware/multiUserProtected");
  3. // When a user is updating or creating a user in multi-user, we need to check if they
  4. // are allowed to do this and that the new or existing user will be at or below their permission level.
  5. // the user executing this function should be an admin or manager.
  6. function validRoleSelection(currentUser = {}, newUserParams = {}) {
  7. if (!newUserParams.hasOwnProperty("role"))
  8. return { valid: true, error: null }; // not updating role, so skip.
  9. if (currentUser.role === ROLES.admin) return { valid: true, error: null };
  10. if (currentUser.role === ROLES.manager) {
  11. const validRoles = [ROLES.manager, ROLES.default];
  12. if (!validRoles.includes(newUserParams.role))
  13. return { valid: false, error: "Invalid role selection for user." };
  14. return { valid: true, error: null };
  15. }
  16. return { valid: false, error: "Invalid condition for caller." };
  17. }
  18. // Check to make sure with this update that includes a role change to an existing admin to a non-admin
  19. // that we still have at least one admin left or else they will lock themselves out.
  20. async function canModifyAdmin(userToModify, updates) {
  21. // if updates don't include role property
  22. // or the user being modified isn't an admin currently
  23. // or the updates role is equal to the users current role.
  24. // skip validation.
  25. if (!updates.hasOwnProperty("role")) return { valid: true, error: null };
  26. if (userToModify.role !== ROLES.admin) return { valid: true, error: null };
  27. if (updates.role === userToModify.role) return { valid: true, error: null };
  28. const adminCount = await User.count({ role: ROLES.admin });
  29. if (adminCount - 1 <= 0)
  30. return {
  31. valid: false,
  32. error: "No system admins will remain if you do this. Update failed.",
  33. };
  34. return { valid: true, error: null };
  35. }
  36. function validCanModify(currentUser, existingUser) {
  37. if (currentUser.role === ROLES.admin) return { valid: true, error: null };
  38. if (currentUser.role === ROLES.manager) {
  39. const validRoles = [ROLES.manager, ROLES.default];
  40. if (!validRoles.includes(existingUser.role))
  41. return { valid: false, error: "Cannot perform that action on user." };
  42. return { valid: true, error: null };
  43. }
  44. return { valid: false, error: "Invalid condition for caller." };
  45. }
  46. module.exports = {
  47. validCanModify,
  48. validRoleSelection,
  49. canModifyAdmin,
  50. };