branchAccess.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. import { isAdminLike as isAdminLikeRole } from "@/lib/frontend/auth/roles";
  8. /**
  9. * @typedef {Object} AuthUser
  10. * @property {string} userId
  11. * @property {string} role
  12. * @property {string|null} branchId
  13. */
  14. export const BRANCH_ACCESS = Object.freeze({
  15. ALLOWED: "allowed",
  16. FORBIDDEN: "forbidden",
  17. });
  18. /**
  19. * Decide whether the given user can access a route branch.
  20. *
  21. * Rules:
  22. * - role "branch": only allowed when routeBranch === user.branchId
  23. * - roles admin-like (admin/superadmin/dev): allowed for any route branch
  24. * - unknown roles or missing required data: forbidden
  25. *
  26. * @param {AuthUser|null} user
  27. * @param {string} routeBranch
  28. * @returns {"allowed"|"forbidden"}
  29. */
  30. export function getBranchAccess(user, routeBranch) {
  31. if (!user || typeof routeBranch !== "string" || !routeBranch) {
  32. return BRANCH_ACCESS.FORBIDDEN;
  33. }
  34. if (user.role === "branch") {
  35. return user.branchId === routeBranch
  36. ? BRANCH_ACCESS.ALLOWED
  37. : BRANCH_ACCESS.FORBIDDEN;
  38. }
  39. if (isAdminLikeRole(user.role)) {
  40. return BRANCH_ACCESS.ALLOWED;
  41. }
  42. return BRANCH_ACCESS.FORBIDDEN;
  43. }