| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- "use client";
- import React from "react";
- /**
- * Auth Context (RHL-020)
- *
- * Purpose:
- * - Provide a tiny, app-wide session state for the UI:
- * - status: "unknown" | "loading" | "authenticated" | "unauthenticated" | "error"
- * - user: { userId, role, branchId } | null
- * - error: string | null
- * - isValidating: boolean (true while a background session re-check runs)
- * - retry: () => void | null (re-run the session check)
- */
- /**
- * @typedef {"unknown"|"loading"|"authenticated"|"unauthenticated"|"error"} AuthStatus
- */
- /**
- * @typedef {Object} AuthUser
- * @property {string} userId
- * @property {string} role
- * @property {string|null} branchId
- * @property {string|null} email
- */
- /**
- * @typedef {Object} AuthState
- * @property {AuthStatus} status
- * @property {AuthUser|null} user
- * @property {string|null} error
- * @property {boolean} isValidating
- * @property {(() => void)|null} retry
- */
- /** @type {AuthState} */
- export const DEFAULT_AUTH_STATE = Object.freeze({
- status: "unknown",
- user: null,
- error: null,
- isValidating: false,
- retry: null,
- });
- const AuthContext = React.createContext(DEFAULT_AUTH_STATE);
- /**
- * Consume the auth context.
- *
- * @returns {AuthState}
- */
- export function useAuth() {
- return React.useContext(AuthContext);
- }
- /**
- * Provider wrapper.
- *
- * @param {{ value: Partial<AuthState>, children: React.ReactNode }} props
- */
- export function AuthProvider({ value, children }) {
- const merged = React.useMemo(() => {
- return { ...DEFAULT_AUTH_STATE, ...(value || {}) };
- }, [value]);
- return <AuthContext.Provider value={merged}>{children}</AuthContext.Provider>;
- }
|