@pagamio/frontend-commons-lib
Version:
Pagamio library for Frontend reusable components like the form engine and table container
231 lines (230 loc) • 7.28 kB
TypeScript
import type { ApiClient } from '../../api';
import type { AuthResponse, CustomAuthConfig } from '../types';
import { TokenManager } from '../utils';
/**
* Registration request payload
* Basic version with required email and password fields
*/
interface RegistrationRequest {
email: string;
password: string;
[key: string]: unknown;
}
/**
* Generic registration request type that can be any object type
* while maintaining backward compatibility with RegistrationRequest
*/
type GenericRegistrationRequest = RegistrationRequest | Record<string, any>;
/**
* Password reset request payload
*/
interface ResetPasswordRequest {
token: string;
newPassword: string;
newPasswordConfirm: string;
}
/**
* Forgot password request payload
*/
interface ForgotPasswordRequest {
email: string;
}
/**
* Password change request
*/
interface PasswordChangeRequest {
currentPassword: string;
newPassword: string;
}
/**
* Configuration for AuthService
* @template T - Type extending CustomAuthConfig for type-safe auth operations
*/
interface AuthServiceConfig<T extends CustomAuthConfig> {
/** Token manager instance for handling auth tokens */
tokenManager: TokenManager<T>;
/** Api Client instance for handling api calls */
apiClient: ApiClient<T>;
/** Base URL for API endpoints */
baseUrl: string;
/** Endpoint configuration */
endpoints: {
login: string;
logout: string;
refresh: string;
validateToken: string;
resetPassword: string;
changePassword: string;
register: string;
verifyEmail: string;
updateProfile: string;
[key: string]: string;
};
/** Storage configuration */
storage?: {
prefix?: string;
keys?: string[];
};
/** Service options */
options?: {
autoRefreshToken?: boolean;
refreshThresholdMs?: number;
maxRefreshAttempts?: number;
};
/** redirect To Login Page */
handleRedirectToLoginPage: () => void;
}
type RequiredEndpoints = Required<AuthServiceConfig<any>['endpoints']>;
/**
* Complete Authentication Service implementation
* Uses shared API client through useApi hook for all operations
*
* @template T - Type extending CustomAuthConfig
*/
export declare class AuthService<T extends CustomAuthConfig> {
/**
* Keeps a reference to the interval to clear it on unmount.
*/
intervalRef: import("react").MutableRefObject<NodeJS.Timeout | null>;
private readonly tokenManager;
private readonly apiClient;
private readonly endpoints;
private readonly storageConfig;
private readonly options;
private readonly handleRedirectToLoginPage;
private refreshAttempts;
constructor(config: AuthServiceConfig<T>);
/**
* Creates a new AuthService instance
* @param config - Service configuration
* @returns Configured AuthService instance
*/
static create<T extends CustomAuthConfig>(config: Omit<AuthServiceConfig<T>, 'tokenManager'>): AuthService<T>;
/**
* Gets all configured endpoints
* @returns Copy of all configured endpoint URLs
*/
getEndpoints(): RequiredEndpoints;
/**
* Updates an endpoint URL
* @param name - Name of the endpoint to update
* @param url - New URL for the endpoint
*/
setEndpoint(name: keyof RequiredEndpoints, url: string): void;
/**
* Adds a new custom endpoint
* @param name - Name for the new endpoint
* @param url - URL for the new endpoint
*/
addEndpoint(name: string, url: string): void;
/**
* Handles user login
* @param credentials - User credentials
* @param remember - Whether to remember the user
* @returns Authentication response with user and token info
*/
login(credentials: T['Credentials'], remember?: boolean): Promise<AuthResponse<T>>;
/**
* Validates if the response is a valid Strapi authentication response
* @param response - API response to validate
* @returns Boolean indicating if response is a valid Strapi auth response
*/
private isStrapiAuthResponse;
/**
* Handles user registration
* @param data - Registration data, can be any object with registration information
* @returns Authentication response if auto-login is enabled
*/
register(data: GenericRegistrationRequest): Promise<AuthResponse<T>>;
/**
* Handles user logout
* @param everywhere - Whether to logout from all devices
*/
logout(everywhere?: boolean): Promise<void>;
/**
* Refreshes authentication tokens
* @returns Whether the refresh was successful
*/
refreshTokens(): Promise<boolean>;
/**
* Gets the access token expiry timestamp
*/
getAccessTokenExpiry(): number | null;
/**
* Changes user password
* @param data - Password change data
*/
changePassword(data: PasswordChangeRequest): Promise<void>;
/**
* Initiates the password reset process
* @param data - Email address for password reset
*/
forgotPassword(data: ForgotPasswordRequest): Promise<void>;
/**
* Completes the password reset process
* @param data - Reset password data including token and new password
*/
resetPassword(data: ResetPasswordRequest): Promise<void>;
/**
* Verifies email with token
* @param token - Email verification token
*/
verifyEmail(token: string): Promise<void>;
/**
* Updates user profile
* @param data - Updated user data
* @returns Updated user info
*/
updateProfile(data: Partial<T['UserInfo']>): Promise<T['UserInfo']>;
/**
* Gets current user data
* @returns Current user info or null if not authenticated
*/
getUser(): T['UserInfo'] | null;
/**
* Gets remember user session option
* @returns remember user session option or null
*/
getRememberUserSessionOption(): boolean | null;
/**
* Validates current session
* @returns Whether the session is valid
*/
validateSession(): Promise<boolean>;
/**
* Gets the URL for an endpoint
*/
private getEndpointUrl;
/**
* Initializes automatic token refresh
*/
private initializeAutoRefresh;
/**
* Stops automatic token refresh
*/
private stopAutoRefresh;
/**
* Clears all authentication data
*/
private clearAuth;
/**
* Storage utility methods
*/
private getStorageKey;
private setStorageItem;
private getStorageItem;
private clearStorage;
/**
* Error handler
*/
private handleError;
}
/**
* Factory function to create an AuthService instance
* @param config - Basic service configuration
* @param tokenManager
* @param apiClient - Shared API client instance
* @returns Configured AuthService instance
*/
export declare function createAuthService<T extends CustomAuthConfig>(config: Omit<AuthServiceConfig<T>, 'tokenManager' | 'apiClient'>, tokenManager: TokenManager<T>, apiClient: ApiClient<T>): AuthService<T>;
export type { AuthServiceConfig, RegistrationRequest, GenericRegistrationRequest, PasswordChangeRequest, ResetPasswordRequest, ForgotPasswordRequest, };