UNPKG

analytica-frontend-lib

Version:

Repositório público dos componentes utilizados nas plataformas da Analytica Ensino

313 lines (310 loc) 10.9 kB
import * as react_jsx_runtime from 'react/jsx-runtime'; import { ReactNode, ComponentType } from 'react'; /** * Interface for basic authentication tokens * * @interface AuthTokens * @property {string} token - Main authentication token * @property {string} refreshToken - Token used to refresh the main token * @property {unknown} [key] - Additional properties that can be included */ interface AuthTokens { token: string; refreshToken: string; [key: string]: unknown; } /** * Interface for basic user information * * @interface AuthUser * @property {string} id - Unique user identifier * @property {string} [name] - Optional user name * @property {string} [email] - Optional user email * @property {unknown} [key] - Additional user properties */ interface AuthUser { id: string; name?: string; email?: string; [key: string]: unknown; } /** * Interface for basic session information * * @interface SessionInfo * @property {string} [institutionId] - Optional institution identifier * @property {string} [profileId] - Optional profile identifier * @property {string} [schoolId] - Optional school identifier * @property {string} [schoolYearId] - Optional school year identifier * @property {string} [classId] - Optional class identifier * @property {unknown} [key] - Additional session properties */ interface SessionInfo { institutionId?: string; profileId?: string; schoolId?: string; schoolYearId?: string; classId?: string; [key: string]: unknown; } /** * Interface for authentication state * * @interface AuthState * @property {boolean} isAuthenticated - Whether the user is authenticated * @property {boolean} isLoading - Whether authentication is being checked * @property {AuthUser | null} [user] - Current user information * @property {SessionInfo | null} [sessionInfo] - Current session information * @property {AuthTokens | null} [tokens] - Current authentication tokens */ interface AuthState { isAuthenticated: boolean; isLoading: boolean; user?: AuthUser | null; sessionInfo?: SessionInfo | null; tokens?: AuthTokens | null; } /** * Interface for authentication context functions and state * * @interface AuthContextType * @extends {AuthState} * @property {() => Promise<boolean>} checkAuth - Function to check authentication status * @property {() => void} signOut - Function to sign out the user */ interface AuthContextType extends AuthState { checkAuth: () => Promise<boolean>; signOut: () => void; } /** * Props for the AuthProvider component * * @interface AuthProviderProps * @property {ReactNode} children - Child components * @property {() => Promise<boolean> | boolean} [checkAuthFn] - Function to check if user is authenticated * @property {() => void} [signOutFn] - Function to handle logout * @property {Partial<AuthState>} [initialAuthState] - Initial authentication state * @property {() => AuthUser | null | undefined} [getUserFn] - Function to get user data * @property {() => SessionInfo | null | undefined} [getSessionFn] - Function to get session info * @property {() => AuthTokens | null | undefined} [getTokensFn] - Function to get tokens */ interface AuthProviderProps { children: ReactNode; /** * Função para verificar se o usuário está autenticado * Deve retornar uma Promise<boolean> */ checkAuthFn?: () => Promise<boolean> | boolean; /** * Função para fazer logout */ signOutFn?: () => void; /** * Estado de autenticação inicial */ initialAuthState?: Partial<AuthState>; /** * Função para obter dados do usuário (opcional) */ getUserFn?: () => AuthUser | null | undefined; /** * Função para obter informações da sessão (opcional) */ getSessionFn?: () => SessionInfo | null | undefined; /** * Função para obter tokens (opcional) */ getTokensFn?: () => AuthTokens | null | undefined; } /** * Authentication provider that manages global auth state * Compatible with any store (Zustand, Redux, Context, etc.) * * @param {AuthProviderProps} props - The provider props * @returns {JSX.Element} The provider component * * @example * ```tsx * <AuthProvider * checkAuthFn={checkAuthFunction} * signOutFn={signOutFunction} * getUserFn={getUserFunction} * > * <App /> * </AuthProvider> * ``` */ declare const AuthProvider: ({ children, checkAuthFn, signOutFn, initialAuthState, getUserFn, getSessionFn, getTokensFn, }: AuthProviderProps) => react_jsx_runtime.JSX.Element; /** * Hook to use the authentication context * * @throws {Error} When used outside of AuthProvider * @returns {AuthContextType} The authentication context * * @example * ```tsx * const { isAuthenticated, user, signOut } = useAuth(); * ``` */ declare const useAuth: () => AuthContextType; /** * Props for the ProtectedRoute component * * @interface ProtectedRouteProps * @property {ReactNode} children - Components to render when authenticated * @property {string} [redirectTo] - Path to redirect when not authenticated (default: '/') * @property {ReactNode} [loadingComponent] - Custom loading component * @property {(authState: AuthState) => boolean} [additionalCheck] - Additional authentication check */ interface ProtectedRouteProps { children: ReactNode; /** * Path para redirecionamento quando não autenticado */ redirectTo?: string; /** * Componente de loading personalizado */ loadingComponent?: ReactNode; /** * Função adicional de verificação (ex: verificar permissões específicas) */ additionalCheck?: (authState: AuthState) => boolean; } /** * Componente para proteger rotas que requerem autenticação * * @example * ```tsx * <ProtectedRoute redirectTo="/login"> * <PainelPage /> * </ProtectedRoute> * ``` */ declare const ProtectedRoute: ({ children, redirectTo, loadingComponent, additionalCheck, }: ProtectedRouteProps) => react_jsx_runtime.JSX.Element | null; /** * Props for the PublicRoute component * * @interface PublicRouteProps * @property {ReactNode} children - Components to render * @property {string} [redirectTo] - Path to redirect to (default: '/painel') * @property {boolean} [redirectIfAuthenticated] - Whether to redirect if authenticated * @property {boolean} [checkAuthBeforeRender] - Whether to check auth before rendering */ interface PublicRouteProps { children: ReactNode; /** * Path para redirecionamento */ redirectTo?: string; /** * Se deve redirecionar quando usuário estiver autenticado */ redirectIfAuthenticated?: boolean; /** * Se deve verificar autenticação antes de renderizar */ checkAuthBeforeRender?: boolean; } /** * Componente para rotas públicas (login, recuperação de senha, etc.) * Opcionalmente redireciona se o usuário já estiver autenticado * * @example * ```tsx * <PublicRoute redirectTo="/painel" redirectIfAuthenticated={true}> * <LoginPage /> * </PublicRoute> * ``` */ declare const PublicRoute: ({ children, redirectTo, redirectIfAuthenticated, checkAuthBeforeRender, }: PublicRouteProps) => react_jsx_runtime.JSX.Element; /** * Higher-Order Component to protect components with authentication * * @template P - Component props type * @param {ComponentType<P>} Component - Component to wrap with authentication * @param {Omit<ProtectedRouteProps, 'children'>} [options] - Protection options * @returns {(props: P) => JSX.Element} Wrapped component * * @example * ```tsx * const ProtectedComponent = withAuth(MyComponent, { * redirectTo: "/login", * loadingComponent: <CustomSpinner /> * }); * ``` */ declare const withAuth: <P extends object>(Component: ComponentType<P>, options?: Omit<ProtectedRouteProps, "children">) => (props: P) => react_jsx_runtime.JSX.Element; /** * Hook for authentication guard with custom checks * * @param {object} [options] - Guard options * @param {boolean} [options.requireAuth=true] - Whether authentication is required * @param {(authState: AuthState) => boolean} [options.customCheck] - Custom check function * @returns {object} Guard result with canAccess, isLoading, and authState * * @example * ```tsx * const { canAccess, isLoading } = useAuthGuard({ * requireAuth: true, * customCheck: (authState) => authState.user?.role === 'admin' * }); * ``` */ declare const useAuthGuard: (options?: { requireAuth?: boolean; customCheck?: (authState: AuthState) => boolean; }) => { canAccess: boolean; isLoading: boolean; authState: AuthContextType; }; /** * Hook to check authentication on specific routes * Useful for conditional checks within components * * @param {string} [fallbackPath='/'] - Path to redirect when not authenticated * @returns {object} Object with isAuthenticated, isLoading, and redirectToLogin function * * @example * ```tsx * const { isAuthenticated, redirectToLogin } = useRouteAuth(); * * if (!isAuthenticated) { * return redirectToLogin(); * } * ``` */ declare const useRouteAuth: (fallbackPath?: string) => { isAuthenticated: boolean; isLoading: boolean; redirectToLogin: () => react_jsx_runtime.JSX.Element; }; /** * Get the root domain from the current window location * Handles localhost and subdomain cases * * @returns {string} The root domain URL */ declare const getRootDomain: () => string; declare const _default: { AuthProvider: ({ children, checkAuthFn, signOutFn, initialAuthState, getUserFn, getSessionFn, getTokensFn, }: AuthProviderProps) => react_jsx_runtime.JSX.Element; ProtectedRoute: ({ children, redirectTo, loadingComponent, additionalCheck, }: ProtectedRouteProps) => react_jsx_runtime.JSX.Element | null; PublicRoute: ({ children, redirectTo, redirectIfAuthenticated, checkAuthBeforeRender, }: PublicRouteProps) => react_jsx_runtime.JSX.Element; withAuth: <P extends object>(Component: ComponentType<P>, options?: Omit<ProtectedRouteProps, "children">) => (props: P) => react_jsx_runtime.JSX.Element; useAuth: () => AuthContextType; useAuthGuard: (options?: { requireAuth?: boolean; customCheck?: (authState: AuthState) => boolean; }) => { canAccess: boolean; isLoading: boolean; authState: AuthContextType; }; useRouteAuth: (fallbackPath?: string) => { isAuthenticated: boolean; isLoading: boolean; redirectToLogin: () => react_jsx_runtime.JSX.Element; }; }; export { type AuthContextType, AuthProvider, type AuthProviderProps, type AuthState, type AuthTokens, type AuthUser, ProtectedRoute, type ProtectedRouteProps, PublicRoute, type PublicRouteProps, type SessionInfo, _default as default, getRootDomain, useAuth, useAuthGuard, useRouteAuth, withAuth };