branchAccess.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * UI-side RBAC decision helpers for branch-based routes (RHL-021).
  3. *
  4. * This module is pure (no React / no Next runtime).
  5. * The UI can use it to decide whether a user may access a given `:branch` segment.
  6. */
  7. /**
  8. * @typedef {Object} AuthUser
  9. * @property {string} userId
  10. * @property {string} role
  11. * @property {string|null} branchId
  12. */
  13. export const BRANCH_ACCESS = Object.freeze({
  14. ALLOWED: "allowed",
  15. FORBIDDEN: "forbidden",
  16. });
  17. /**
  18. * Decide whether the given user can access a route branch.
  19. *
  20. * Rules:
  21. * - role "branch": only allowed when routeBranch === user.branchId
  22. * - role "admin" / "dev": allowed for any route branch
  23. * - unknown roles or missing required data: forbidden
  24. *
  25. * @param {AuthUser|null} user
  26. * @param {string} routeBranch
  27. * @returns {"allowed"|"forbidden"}
  28. */
  29. export function getBranchAccess(user, routeBranch) {
  30. if (!user || typeof routeBranch !== "string" || !routeBranch) {
  31. return BRANCH_ACCESS.FORBIDDEN;
  32. }
  33. if (user.role === "branch") {
  34. return user.branchId === routeBranch
  35. ? BRANCH_ACCESS.ALLOWED
  36. : BRANCH_ACCESS.FORBIDDEN;
  37. }
  38. if (user.role === "admin" || user.role === "dev") {
  39. return BRANCH_ACCESS.ALLOWED;
  40. }
  41. return BRANCH_ACCESS.FORBIDDEN;
  42. }