analytica-frontend-lib
Version:
Repositório público dos componentes utilizados nas plataformas da Analytica Ensino
324 lines • 11.2 kB
TypeScript
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
*/
export 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
*/
export 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
*/
export 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
*/
export 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
*/
export 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
*/
export 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>
* ```
*/
export declare const AuthProvider: ({ children, checkAuthFn, signOutFn, initialAuthState, getUserFn, getSessionFn, getTokensFn, }: AuthProviderProps) => import("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();
* ```
*/
export 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
*/
export 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>
* ```
*/
export declare const ProtectedRoute: ({ children, redirectTo, loadingComponent, additionalCheck, }: ProtectedRouteProps) => import("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
*/
export 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>
* ```
*/
export declare const PublicRoute: ({ children, redirectTo, redirectIfAuthenticated, checkAuthBeforeRender, }: PublicRouteProps) => import("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 />
* });
* ```
*/
export declare const withAuth: <P extends object>(Component: ComponentType<P>, options?: Omit<ProtectedRouteProps, "children">) => (props: P) => import("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'
* });
* ```
*/
export 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();
* }
* ```
*/
export declare const useRouteAuth: (fallbackPath?: string) => {
isAuthenticated: boolean;
isLoading: boolean;
redirectToLogin: () => import("react/jsx-runtime").JSX.Element;
};
/**
* Get the root domain from the current window location
* Handles localhost, IP addresses, and subdomain cases, including Brazilian .com.br domains
*
* @returns {string} The root domain URL
*
* @example
* ```typescript
* // Domain examples
* aluno.analiticaensino.com.br -> analiticaensino.com.br
* subdomain.example.com -> example.com
*
* // IP address examples
* 127.0.0.1:3000 -> 127.0.0.1:3000
* [::1]:8080 -> [::1]:8080
*
* // Localhost examples
* localhost:3000 -> localhost:3000
* ```
*/
export declare const getRootDomain: () => string;
declare const _default: {
AuthProvider: ({ children, checkAuthFn, signOutFn, initialAuthState, getUserFn, getSessionFn, getTokensFn, }: AuthProviderProps) => import("react/jsx-runtime").JSX.Element;
ProtectedRoute: ({ children, redirectTo, loadingComponent, additionalCheck, }: ProtectedRouteProps) => import("react/jsx-runtime").JSX.Element | null;
PublicRoute: ({ children, redirectTo, redirectIfAuthenticated, checkAuthBeforeRender, }: PublicRouteProps) => import("react/jsx-runtime").JSX.Element;
withAuth: <P extends object>(Component: ComponentType<P>, options?: Omit<ProtectedRouteProps, "children">) => (props: P) => import("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: () => import("react/jsx-runtime").JSX.Element;
};
};
export default _default;
//# sourceMappingURL=Auth.d.ts.map