UNPKG

@gsarthak783/accesskit-auth

Version:

JavaScript/TypeScript SDK for AccessKit Authentication System - Easy auth integration for any project

296 lines (292 loc) 7.92 kB
interface User { id: string; email: string; firstName: string; lastName: string; username?: string; displayName?: string; avatar?: string; isVerified: boolean; isActive: boolean; customFields?: Record<string, any>; createdAt: string; lastLogin?: string; } interface CreateUserData { email: string; password: string; firstName: string; lastName: string; username?: string; customFields?: Record<string, any>; } interface LoginCredentials { email: string; password: string; } interface UpdateUserData { firstName?: string; lastName?: string; displayName?: string; avatar?: string; username?: string; customFields?: Record<string, any>; } interface ChangePasswordData { currentPassword: string; newPassword: string; } interface UpdateEmailData { newEmail: string; password: string; } interface ReauthenticateData { password: string; } interface AuthResponse { success: boolean; message?: string; data: { user: User; tokens: { accessToken: string; refreshToken: string; }; needsVerification?: boolean; }; } interface ApiResponse<T = any> { success: boolean; data?: T; message?: string; errors?: Array<{ field: string; message: string; }>; } interface AuthConfig { apiKey: string; baseUrl?: string; projectId?: string; timeout?: number; } interface TokenStorage { getAccessToken(): string | null; setAccessToken(token: string): void; getRefreshToken(): string | null; setRefreshToken(token: string): void; clearTokens(): void; } type AuthEvent = 'login' | 'logout' | 'register' | 'token_refresh' | 'profile_update' | 'error' | 'authStateChange' | 'reauthenticate'; interface AuthEventData { user?: User; error?: Error; timestamp: number; isAuthenticated?: boolean; } interface PaginationOptions { page?: number; limit?: number; } interface PaginatedResponse<T> { data: T[]; pagination: { current: number; pages: number; total: number; }; } interface ExportOptions { format?: 'json' | 'csv'; includeCustomFields?: boolean; dateRange?: { from: string; to: string; }; } interface ImportOptions { format?: 'json' | 'csv'; updateExisting?: boolean; skipInvalid?: boolean; } interface ExportData { users: User[]; metadata: { exportedAt: string; totalCount: number; projectId: string; }; } type EventListener = (data: AuthEventData) => void; declare class AuthClient { private config; private http; private storage; private eventListeners; private refreshPromise; private currentUser; private initialized; private initPromise; constructor(config: AuthConfig, storage?: TokenStorage); /** * Initialize auth state by checking stored tokens */ private initialize; /** * Get the current authenticated user (from memory, no API call) */ getCurrentUser(): User | null; /** * Check if user is authenticated (has valid tokens) */ isAuthenticated(): boolean; /** * Subscribe to auth state changes * Returns an unsubscribe function */ onAuthStateChange(callback: (user: User | null, isAuthenticated: boolean) => void): () => void; /** * Create axios instance with default configuration */ private createHttpClient; /** * Setup request/response interceptors for automatic token handling */ private setupInterceptors; /** * Event system for auth state changes */ on(event: AuthEvent, listener: EventListener): void; off(event: AuthEvent, listener: EventListener): void; private emit; /** * Register a new user */ register(userData: CreateUserData): Promise<AuthResponse>; /** * Login user */ login(credentials: LoginCredentials): Promise<AuthResponse>; /** * Logout user */ logout(): Promise<void>; /** * Get current user profile */ getProfile(): Promise<User>; /** * Update user profile */ updateProfile(data: UpdateUserData): Promise<User>; /** * Refresh access token */ refreshToken(): Promise<string>; private performTokenRefresh; /** * Request password reset */ requestPasswordReset(email: string): Promise<void>; /** * Reset password with token */ resetPassword(token: string, password: string): Promise<void>; /** * Verify email address */ verifyEmail(token: string): Promise<void>; /** * Update user password */ updatePassword(data: ChangePasswordData): Promise<void>; /** * Update user email */ updateEmail(data: UpdateEmailData): Promise<{ email: string; isVerified: boolean; }>; /** * Reauthenticate user with credentials * This is useful for sensitive operations that require password confirmation */ reauthenticateWithCredential(data: ReauthenticateData): Promise<{ authenticated: boolean; authenticatedAt: string; }>; /** * Get current access token */ getAccessToken(): string | null; /** * Export user data (requires admin access) */ exportUsers(options?: ExportOptions): Promise<ExportData>; /** * Import user data (requires admin access) */ importUsers(data: ExportData, options?: ImportOptions): Promise<ApiResponse>; /** * Get all users (admin only, with pagination) */ getUsers(options?: PaginationOptions): Promise<PaginatedResponse<User>>; /** * Delete a user (admin only) */ deleteUser(userId: string): Promise<void>; /** * Update user status (admin only) */ updateUserStatus(userId: string, isActive: boolean): Promise<User>; /** * Get user by ID (admin only) */ getUser(userId: string): Promise<User>; } /** * Default localStorage-based token storage * Works in browsers and React Native with AsyncStorage polyfill */ declare class LocalTokenStorage implements TokenStorage { private accessTokenKey; private refreshTokenKey; constructor(keyPrefix?: string); getAccessToken(): string | null; setAccessToken(token: string): void; getRefreshToken(): string | null; setRefreshToken(token: string): void; clearTokens(): void; } /** * Memory-based token storage (tokens lost on page refresh) * Useful for server-side rendering or when localStorage is not available */ declare class MemoryTokenStorage implements TokenStorage { private accessToken; private refreshToken; getAccessToken(): string | null; setAccessToken(token: string): void; getRefreshToken(): string | null; setRefreshToken(token: string): void; clearTokens(): void; } /** * Cookie-based token storage (for SSR or when you prefer cookies) * Note: Requires proper HTTPS and SameSite configuration in production */ declare class CookieTokenStorage implements TokenStorage { private accessTokenKey; private refreshTokenKey; constructor(keyPrefix?: string); private getCookie; private setCookie; private deleteCookie; getAccessToken(): string | null; setAccessToken(token: string): void; getRefreshToken(): string | null; setRefreshToken(token: string): void; clearTokens(): void; } export { AuthClient, CookieTokenStorage, LocalTokenStorage, MemoryTokenStorage, AuthClient as default }; export type { ApiResponse, AuthConfig, AuthEvent, AuthEventData, AuthResponse, ChangePasswordData, CreateUserData, ExportData, ExportOptions, ImportOptions, LoginCredentials, PaginatedResponse, PaginationOptions, ReauthenticateData, TokenStorage, UpdateEmailData, UpdateUserData, User };