@digilogiclabs/saas-factory-auth
Version:
Modern authentication package for Next.js 15+ and React 18.2+/19+ applications with React Native 0.72+ support using Supabase and Firebase
498 lines (485 loc) • 16.1 kB
TypeScript
import React from 'react';
import * as _supabase_supabase_js from '@supabase/supabase-js';
import { D as Database } from './index-BeqpJTCy.js';
export { c as createSupabaseServerClient } from './index-BeqpJTCy.js';
import { NextRequest, NextResponse } from 'next/server.js';
import 'next/dist/server/web/spec-extension/adapters/request-cookies';
/**
* Authentication error types for better error handling
*/
declare enum AuthErrorType {
INVALID_CREDENTIALS = "INVALID_CREDENTIALS",
USER_NOT_FOUND = "USER_NOT_FOUND",
EMAIL_ALREADY_EXISTS = "EMAIL_ALREADY_EXISTS",
WEAK_PASSWORD = "WEAK_PASSWORD",
NETWORK_ERROR = "NETWORK_ERROR",
PROVIDER_ERROR = "PROVIDER_ERROR",
CONFIGURATION_ERROR = "CONFIGURATION_ERROR",
VALIDATION_ERROR = "VALIDATION_ERROR",
UNKNOWN = "UNKNOWN"
}
/**
* Custom authentication error class
*/
declare class AuthError extends Error {
readonly type: AuthErrorType;
readonly originalError?: unknown | undefined;
readonly context?: Record<string, unknown> | undefined;
readonly timestamp: Date;
readonly code: string;
constructor(type: AuthErrorType, message: string, originalError?: unknown | undefined, context?: Record<string, unknown> | undefined);
/**
* Convert error to JSON for logging/debugging
*/
toJSON(): {
name: string;
type: AuthErrorType;
code: string;
message: string;
timestamp: string;
context: Record<string, unknown> | undefined;
originalError: {
name: string;
message: string;
stack: string | undefined;
} | {
message: string;
name?: never;
stack?: never;
} | undefined;
};
/**
* Check if error is of a specific type
*/
isType(type: AuthErrorType): boolean;
/**
* Check if error is retryable
*/
isRetryable(): boolean;
}
/**
* OAuth provider types - re-export from types for backward compatibility
*/
type OAuthProvider$1 = 'google' | 'github' | 'facebook' | 'twitter' | 'discord' | 'apple' | 'microsoft' | 'linkedin' | 'spotify' | 'twitch' | 'slack' | 'notion';
/**
* Authentication provider interface that abstracts authentication operations
* across different backends (Supabase, Firebase, etc.)
*/
interface IAuthProvider {
/**
* Sign in with email and password
* @param email User's email address
* @param password User's password (required for email/password authentication)
* @returns Promise resolving to an object containing user, session, and error
*/
signIn(email: string, password: string): Promise<{
user: User | null;
session: AuthSession | null;
error: AuthError | null;
}>;
/**
* Sign up with email and password
* @param email User's email address
* @param password User's password (required for email/password authentication)
* @returns Promise resolving to an object containing user, session, and error
*/
signUp(email: string, password: string): Promise<{
user: User | null;
session: AuthSession | null;
error: AuthError | null;
}>;
/**
* Sign in with OAuth provider
* @param provider OAuth provider name
* @param redirectTo Optional redirect URL after authentication
* @returns Promise that resolves when OAuth flow is initiated
*/
signInWithOAuth(provider: OAuthProvider$1, redirectTo?: string): Promise<void>;
/**
* Sign in with magic link (passwordless authentication)
* @param email User's email address
* @param redirectTo Optional redirect URL after email verification
* @returns Promise that resolves when magic link is sent
*/
signInWithMagicLink(email: string, redirectTo?: string): Promise<void>;
/**
* Sign out the current user
* @returns Promise resolving to an object containing error
*/
signOut(): Promise<{
error: AuthError | null;
}>;
/**
* Get the current authenticated user
* @returns Promise resolving to the current user or null if not authenticated
*/
getUser(): Promise<User | null>;
/**
* Get the current authentication session
* @returns Promise resolving to the current session or null if not authenticated
*/
getSession(): Promise<AuthSession | null>;
/**
* Send password reset email
* @param email User's email address
* @returns Promise resolving to an object containing error
*/
resetPassword(email: string): Promise<{
error: AuthError | null;
}>;
/**
* Update user profile information
* @param updates Partial user data to update
* @returns Promise resolving to updated user and error information
*/
updateProfile(updates: {
name?: string;
firstName?: string;
lastName?: string;
fullName?: string;
avatar?: string;
phone?: string;
website?: string;
bio?: string;
[key: string]: unknown;
}): Promise<{
user: User | null;
error: AuthError | null;
}>;
/**
* Listen for authentication state changes
* @param callback Function called when auth state changes
* @returns Object containing subscription data for cleanup
*/
onAuthStateChange(callback: (event: AuthEvent, session: AuthSession | null) => void): {
unsubscribe: () => void;
};
/**
* Validate provider configuration
* @returns Promise that resolves if configuration is valid
*/
validateConfiguration?(): Promise<void>;
}
/**
* Base user profile information
*/
interface UserProfile {
/** User's display name */
name?: string | null;
/** User's first name */
firstName?: string | null;
/** User's last name */
lastName?: string | null;
/** User's full name */
fullName?: string | null;
/** User's avatar/profile picture URL */
avatar?: string | null;
/** User's phone number */
phone?: string | null;
/** User's date of birth */
dateOfBirth?: string | null;
/** User's preferred language */
locale?: string | null;
/** User's timezone */
timezone?: string | null;
/** User's website URL */
website?: string | null;
/** User's bio/description */
bio?: string | null;
}
/**
* User metadata from OAuth providers
*/
interface UserMetadata {
/** Provider-specific user data */
[provider: string]: {
/** Provider's unique user ID */
id?: string;
/** Username on the provider */
username?: string;
/** Provider-specific data */
raw?: Record<string, unknown>;
};
}
/**
* User interface representing authenticated user data
*/
interface User extends UserProfile {
/** Unique user identifier */
id: string;
/** User's email address */
email?: string | undefined;
/** User's email verification status */
emailVerified?: boolean;
/** User roles for RBAC */
roles?: UserRole[];
/** User permissions */
permissions?: string[];
/** Account creation timestamp */
createdAt?: string | Date;
/** Last update timestamp */
updatedAt?: string | Date;
/** Last sign-in timestamp */
lastSignInAt?: string | Date;
/** OAuth provider metadata */
providerData?: UserMetadata;
/** Custom user attributes */
customClaims?: Record<string, unknown>;
/** Two-factor authentication enabled */
twoFactorEnabled?: boolean;
/** User account status */
status?: 'active' | 'inactive' | 'suspended' | 'pending';
/** Provider-specific data for backward compatibility */
[key: string]: unknown;
}
/**
* Authentication session containing user and token information
*/
interface AuthSession {
user: User;
access_token: string;
refresh_token?: string | undefined;
expires_at?: number | undefined;
}
/**
* Authentication events that can occur during auth state changes
*/
declare enum AuthEvent {
SIGNED_IN = "SIGNED_IN",
SIGNED_OUT = "SIGNED_OUT",
TOKEN_REFRESHED = "TOKEN_REFRESHED",
USER_UPDATED = "USER_UPDATED"
}
/**
* OAuth provider types supported by the auth system
*/
type OAuthProvider = 'google' | 'github' | 'facebook' | 'twitter' | 'discord' | 'apple' | 'microsoft' | 'linkedin' | 'spotify' | 'twitch' | 'slack' | 'notion';
/**
* Authentication form modes
*/
type AuthMode = 'signIn' | 'signUp' | 'resetPassword' | 'magicLink';
/**
* User roles for RBAC (Role-Based Access Control)
*/
type UserRole = 'admin' | 'user' | 'moderator' | 'guest' | 'owner' | 'editor' | 'viewer' | 'contributor' | 'manager' | 'developer' | 'analyst' | 'support';
/**
* Password validation configuration
*/
interface PasswordConfig {
minLength?: number;
requireUppercase?: boolean;
requireLowercase?: boolean;
requireNumbers?: boolean;
requireSpecialChars?: boolean;
}
/**
* Authentication configuration interface
*/
interface AuthConfig {
supabaseUrl?: string;
supabaseAnonKey?: string;
firebaseApiKey?: string;
firebaseAuthDomain?: string;
firebaseProjectId?: string;
redirectTo?: string;
redirectUrl?: string;
autoRefreshToken?: boolean;
persistSession?: boolean;
maxLoginAttempts?: number;
lockoutDuration?: number;
jwtExpiryTime?: number;
require2FA?: boolean;
password?: PasswordConfig;
passwordRequirements?: PasswordConfig;
}
/**
* Props for AuthForm component
*/
interface AuthFormProps {
defaultMode?: AuthMode;
onSuccess?: () => void;
onError?: (error: Error) => void;
redirectTo?: string;
providers?: OAuthProvider[];
allowMagicLink?: boolean;
className?: string;
}
interface AuthStore {
user: User | null;
session: AuthSession | null;
loading: boolean;
error: Error | null;
setUser: (user: User | null) => void;
setSession: (session: AuthSession | null) => void;
setLoading: (loading: boolean) => void;
setError: (error: Error | null) => void;
setAuthProvider: (provider: IAuthProvider) => void;
signIn: (email: string, password: string) => Promise<void>;
signUp: (email: string, password: string) => Promise<void>;
signOut: () => Promise<void>;
resetPassword: (email: string) => Promise<void>;
updateProfile: (updates: {
name?: string;
firstName?: string;
lastName?: string;
fullName?: string;
avatar?: string;
phone?: string;
website?: string;
bio?: string;
[key: string]: unknown;
}) => Promise<User | null>;
signInWithOAuth: (provider: OAuthProvider, redirectTo?: string) => Promise<void>;
signInWithMagicLink: (email: string, redirectTo?: string) => Promise<void>;
getUser: () => Promise<User | null>;
getSession: () => Promise<AuthSession | null>;
onAuthStateChange: (callback: (event: AuthEvent, session: AuthSession | null) => void) => {
unsubscribe: () => void;
};
}
interface AuthProviderProps {
children: React.ReactNode;
onAuthChange?: (event: AuthEvent) => void;
autoSignIn?: boolean;
}
declare const AuthProvider: React.FC<AuthProviderProps>;
interface AuthState extends AuthStore {
authProvider: IAuthProvider | null;
setAuthProvider: (provider: IAuthProvider) => void;
setSession: (session: AuthSession | null) => void;
}
declare const useAuth: () => AuthState;
/**
* Storage interface for cross-platform compatibility
*/
interface IAuthStorage {
getItem(key: string): Promise<string | null>;
setItem(key: string, value: string): Promise<void>;
removeItem(key: string): Promise<void>;
}
/**
* Supported authentication provider types
*/
type AuthProviderType = 'supabase' | 'firebase';
/**
* Configuration interface for provider factory
*/
interface AuthProviderConfig {
/** Provider type to use */
type: AuthProviderType;
/** Whether to validate configuration on creation */
validateConfig?: boolean;
/** Whether to use singleton pattern */
useSingleton?: boolean;
/** Custom storage implementation (optional) */
storage?: IAuthStorage;
}
/**
* Factory class for creating authentication providers with improved patterns
*/
declare class AuthProviderFactory {
private static instances;
/**
* Gets provider based on environment variables (auto-detection)
* @param config Optional configuration overrides
* @returns Authentication provider instance
*/
static getProviderFromEnvironment(config?: Partial<AuthProviderConfig>): Promise<IAuthProvider>;
/**
* Gets provider instance with configuration
* @param config Provider configuration
* @returns Authentication provider instance
*/
static getProvider(config: AuthProviderConfig): Promise<IAuthProvider>;
/**
* Creates a new provider instance without caching
* @param type Provider type
* @param storage Optional custom storage implementation
* @returns Authentication provider instance
*/
static createProvider(type: AuthProviderType, storage?: IAuthStorage): IAuthProvider;
/**
* Detects provider type from environment variables
* @returns Detected provider type
*/
private static detectProviderFromEnvironment;
/**
* Gets explicit provider from environment variables (platform-agnostic)
*/
private static getExplicitProvider;
/**
* Validates if a string is a valid provider type
* @param type String to validate
* @returns True if valid provider type
*/
private static isValidProviderType;
/**
* Gets list of supported provider types
* @returns Array of supported provider types
*/
static getSupportedProviders(): AuthProviderType[];
/**
* Checks if a provider type is supported
* @param type Provider type to check
* @returns True if supported
*/
static isProviderSupported(type: string): type is AuthProviderType;
/**
* Clears singleton instances (useful for testing)
*/
static clearInstances(): void;
/**
* Gets current singleton instances (useful for debugging)
* @returns Map of current instances
*/
static getInstances(): Map<AuthProviderType, IAuthProvider>;
}
/**
* Authentication actions for templates
* These are convenient wrapper functions around the store methods
*/
/**
* Sign up with email and password
*/
declare const signUp: (email: string, password: string) => Promise<void>;
/**
* Sign in with email and password
*/
declare const signIn: (email: string, password: string) => Promise<void>;
/**
* Sign out the current user
*/
declare const signOut: () => Promise<void>;
/**
* Reset password for given email
*/
declare const resetPassword: (email: string) => Promise<void>;
/**
* Update user profile
* Fully implemented with Supabase-first approach and Firebase fallback
*/
declare const updateProfile: (updates: {
name?: string;
firstName?: string;
lastName?: string;
fullName?: string;
avatar?: string;
phone?: string;
website?: string;
bio?: string;
[key: string]: unknown;
}) => Promise<User | null>;
/**
* Sign in with OAuth provider
*/
declare const signInWithOAuth: (provider: OAuthProvider, redirectTo?: string) => Promise<void>;
/**
* Sign in with magic link
*/
declare const signInWithMagicLink: (email: string, redirectTo?: string) => Promise<void>;
declare const createClient: () => _supabase_supabase_js.SupabaseClient<Database, "public", any>;
declare function withAuth(request: NextRequest): {
response: NextResponse<unknown>;
supabase: _supabase_supabase_js.SupabaseClient<any, "public", any>;
};
export { type AuthConfig, AuthEvent, type AuthFormProps, type AuthMode, AuthProvider, AuthProviderFactory, type AuthSession, type AuthStore, type OAuthProvider, type PasswordConfig, type User, type UserRole, createClient as createSupabaseClient, resetPassword, signIn, signInWithMagicLink, signInWithOAuth, signOut, signUp, updateProfile, useAuth, withAuth };