UNPKG

@labdigital/federated-token-react

Version:
81 lines (78 loc) 2.81 kB
import * as react_jsx_runtime from 'react/jsx-runtime'; type CookieNames = { guestData: string; userData: string; guestRefreshTokenExists: string; userRefreshTokenExists: string; }; type TokenValues = Record<string, any>; type AuthContextType = { isAuthenticated: boolean; hasToken: boolean; values: TokenValues | null; loading: boolean; logout: () => Promise<void>; validateLocalToken: () => void; checkToken: () => Promise<void>; refreshToken: (signal?: AbortSignal) => Promise<boolean>; }; type AuthProviderProps = { cookieNames?: CookieNames; logoutHandler?: () => void; refreshHandler?: (signal?: AbortSignal) => Promise<boolean>; refreshTimeoutMs?: number; refreshTokenEndpoint?: string; refreshTokenMutation?: string; logoutEndpoint?: string; logoutMutation?: string; }; /** * Provider that handles authentication state. * * @remarks * This component manages the client side authentication state and flow for the application. * * @flow * 1. Component Mount: * - The `validateLocalToken` function is called. * - It checks the local token without making a request. * - The auth state is updated based on the local token. * * 2. Request Handling: * - Before making a request, `checkToken` is called to verify token status with the server. * - If the access token is expired or invalid: * a. The server attempts to use the refresh token to obtain a new access token. * b. If successful, a new access token is returned and the auth state is updated. * c. If unsuccessful, the auth state is updated to unauthenticated. * - The request is then made with the current token state. * - The auth state is updated based on the server's response. * * @param props.apiHostname - api hostname used to fetch token status from the api */ declare function AuthProvider({ children, options, }: { children: React.ReactNode; options: AuthProviderProps; }): react_jsx_runtime.JSX.Element; /** * Custom hook to access authentication context. * * @returns An object containing: * - isAuthenticated: boolean indicating if the user is authenticated * - values: object containing all values from the token * - loading: boolean indicating if the authentication state is being loaded * - logout: function to log out the current user * - refreshToken: function to refresh the authentication token * * @throws {Error} If used outside of an AuthProvider * * @example * const { isAuthenticated, values, logout } = useAuth(); * * if (isAuthenticated) { * console.log(`Welcome, ${values.givenName}!`); * } else { * console.log('Please log in.'); * } */ declare function useAuth(): AuthContextType; export { AuthProvider, type AuthProviderProps, useAuth };