BranchGuard.jsx 988 B

1234567891011121314151617181920212223242526272829303132333435
  1. "use client";
  2. import React from "react";
  3. import { useAuth } from "@/components/auth/authContext";
  4. import ForbiddenView from "@/components/system/ForbiddenView";
  5. import {
  6. getBranchAccess,
  7. BRANCH_ACCESS,
  8. } from "@/lib/frontend/rbac/branchAccess";
  9. /**
  10. * BranchGuard (RHL-021)
  11. *
  12. * UI-side RBAC guard for branch-based routes.
  13. *
  14. * This guard assumes that AuthProvider already handled session checks and redirects.
  15. * Therefore:
  16. * - If the auth state is not authenticated yet, we render children (AuthProvider gating).
  17. * - If authenticated, we enforce branch-level RBAC for role="branch".
  18. */
  19. export default function BranchGuard({ branch, children }) {
  20. const { status, user } = useAuth();
  21. const access = React.useMemo(() => {
  22. if (status !== "authenticated") return BRANCH_ACCESS.ALLOWED;
  23. return getBranchAccess(user, branch);
  24. }, [status, user, branch]);
  25. if (access === BRANCH_ACCESS.FORBIDDEN) {
  26. return <ForbiddenView attemptedBranch={branch} />;
  27. }
  28. return children;
  29. }