authContext.jsx 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. "use client";
  2. import React from "react";
  3. /**
  4. * Auth Context (RHL-020)
  5. *
  6. * Purpose:
  7. * - Provide a tiny, app-wide session state for the UI:
  8. * - status: "unknown" | "loading" | "authenticated" | "unauthenticated" | "error"
  9. * - user: { userId, role, branchId } | null
  10. * - error: string | null
  11. * - retry: () => void | null (optional callback to re-run the session check)
  12. *
  13. * Why this file exists:
  14. * - Keep auth state accessible without prop-drilling.
  15. * - Keep the context/hook independent from Next.js routing.
  16. */
  17. /**
  18. * @typedef {"unknown"|"loading"|"authenticated"|"unauthenticated"|"error"} AuthStatus
  19. */
  20. /**
  21. * @typedef {Object} AuthUser
  22. * @property {string} userId
  23. * @property {string} role
  24. * @property {string|null} branchId
  25. */
  26. /**
  27. * @typedef {Object} AuthState
  28. * @property {AuthStatus} status
  29. * @property {AuthUser|null} user
  30. * @property {string|null} error
  31. * @property {(() => void)|null} retry
  32. */
  33. /** @type {AuthState} */
  34. export const DEFAULT_AUTH_STATE = Object.freeze({
  35. status: "unknown",
  36. user: null,
  37. error: null,
  38. retry: null,
  39. });
  40. const AuthContext = React.createContext(DEFAULT_AUTH_STATE);
  41. /**
  42. * Consume the auth context.
  43. *
  44. * @returns {AuthState}
  45. */
  46. export function useAuth() {
  47. return React.useContext(AuthContext);
  48. }
  49. /**
  50. * Provider wrapper.
  51. *
  52. * @param {{ value: Partial<AuthState>, children: React.ReactNode }} props
  53. */
  54. export function AuthProvider({ value, children }) {
  55. const merged = React.useMemo(() => {
  56. return { ...DEFAULT_AUTH_STATE, ...(value || {}) };
  57. }, [value]);
  58. return <AuthContext.Provider value={merged}>{children}</AuthContext.Provider>;
  59. }