@mguay/nestjs-better-auth
Version:
Better Auth for NestJS
180 lines (173 loc) • 6.59 kB
TypeScript
import { CustomDecorator, createParamDecorator, CanActivate, ExecutionContext, ModuleMetadata, Type, NestModule, OnModuleInit, MiddlewareConsumer, DynamicModule, Provider } from '@nestjs/common';
import { createAuthMiddleware, getSession } from 'better-auth/api';
import { Auth } from 'better-auth';
import { Reflector, DiscoveryService, MetadataScanner, HttpAdapterHost } from '@nestjs/core';
/**
* Marks a route or a controller as public, allowing unauthenticated access.
* When applied, the AuthGuard will skip authentication checks.
*/
declare const Public: () => CustomDecorator<string>;
/**
* Marks a route or a controller as having optional authentication.
* When applied, the AuthGuard will allow the request to proceed
* even if no session is present.
*/
declare const Optional: () => CustomDecorator<string>;
/**
* Parameter decorator that extracts the user session from the request.
* Provides easy access to the authenticated user's session data in controller methods.
*/
declare const Session: ReturnType<typeof createParamDecorator>;
/**
* Represents the context object passed to hooks.
* This type is derived from the parameters of the createAuthMiddleware function.
*/
type AuthHookContext = Parameters<Parameters<typeof createAuthMiddleware>[0]>[0];
/**
* Registers a method to be executed before a specific auth route is processed.
* @param path - The auth route path that triggers this hook (must start with '/')
*/
declare const BeforeHook: (path: `/${string}`) => CustomDecorator<symbol>;
/**
* Registers a method to be executed after a specific auth route is processed.
* @param path - The auth route path that triggers this hook (must start with '/')
*/
declare const AfterHook: (path: `/${string}`) => CustomDecorator<symbol>;
/**
* Class decorator that marks a provider as containing hook methods.
* Must be applied to classes that use BeforeHook or AfterHook decorators.
*/
declare const Hook: () => ClassDecorator;
/**
* NestJS service that provides access to the Better Auth instance
* Use generics to support auth instances extended by plugins
*/
declare class AuthService<T extends {
api: T["api"];
} = Auth> {
private readonly auth;
constructor(auth: T);
/**
* Returns the API endpoints provided by the auth instance
*/
get api(): T["api"];
/**
* Returns the complete auth instance
* Access this for plugin-specific functionality
*/
get instance(): T;
}
/**
* Type representing a valid user session after authentication
* Excludes null and undefined values from the session return type
*/
type UserSession = NonNullable<Awaited<ReturnType<ReturnType<typeof getSession>>>>;
/**
* NestJS guard that handles authentication for protected routes
* Can be configured with @Public() or @Optional() decorators to modify authentication behavior
*/
declare class AuthGuard implements CanActivate {
private readonly reflector;
private readonly auth;
constructor(reflector: Reflector, auth: Auth);
/**
* Validates if the current request is authenticated
* Attaches session and user information to the request object
* @param context - The execution context of the current request
* @returns True if the request is authorized to proceed, throws an error otherwise
*/
canActivate(context: ExecutionContext): Promise<boolean>;
}
/**
* Configuration options for the AuthModule
*/
type AuthModuleOptions = {
disableExceptionFilter?: boolean;
disableTrustedOriginsCors?: boolean;
disableBodyParser?: boolean;
};
/**
* Factory for creating Auth instance and module options asynchronously
*/
interface AuthModuleAsyncOptions extends Pick<ModuleMetadata, "imports"> {
/**
* Factory function that returns an object with auth instance and optional module options
*/
useFactory: (...args: unknown[]) => Promise<{
auth: any;
options?: AuthModuleOptions;
}> | {
auth: any;
options?: AuthModuleOptions;
};
/**
* Providers to inject into the factory function
*/
inject?: (string | symbol | Type<unknown>)[];
/**
* Use an existing provider class
*/
useClass?: Type<{
createAuthOptions(): Promise<{
auth: any;
options?: AuthModuleOptions;
}> | {
auth: any;
options?: AuthModuleOptions;
};
}>;
/**
* Use an existing provider
*/
useExisting?: Type<{
createAuthOptions(): Promise<{
auth: any;
options?: AuthModuleOptions;
}> | {
auth: any;
options?: AuthModuleOptions;
};
}>;
}
/**
* NestJS module that integrates the Auth library with NestJS applications.
* Provides authentication middleware, hooks, and exception handling.
*/
declare class AuthModule implements NestModule, OnModuleInit {
private readonly auth;
private readonly discoveryService;
private readonly metadataScanner;
private readonly adapter;
private readonly options;
private readonly logger;
constructor(auth: Auth, discoveryService: DiscoveryService, metadataScanner: MetadataScanner, adapter: HttpAdapterHost, options: AuthModuleOptions);
onModuleInit(): void;
configure(consumer: MiddlewareConsumer): void;
private setupHooks;
/**
* Static factory method to create and configure the AuthModule.
* @param auth - The Auth instance to use
* @param options - Configuration options for the module
*/
static forRoot(auth: any, options?: AuthModuleOptions): DynamicModule;
/**
* Static factory method to create and configure the AuthModule asynchronously.
* @param options - Async configuration options for the module
*/
static forRootAsync(options: AuthModuleAsyncOptions): {
global: boolean;
module: typeof AuthModule;
imports?: ModuleMetadata["imports"];
providers: Provider[];
exports: (Provider | typeof AuthService)[];
};
private static createAsyncProviders;
private static createExceptionFilterProvider;
}
declare const BEFORE_HOOK_KEY: symbol;
declare const AFTER_HOOK_KEY: symbol;
declare const HOOK_KEY: symbol;
declare const AUTH_INSTANCE_KEY: symbol;
declare const AUTH_MODULE_OPTIONS_KEY: symbol;
export { AFTER_HOOK_KEY, AUTH_INSTANCE_KEY, AUTH_MODULE_OPTIONS_KEY, AfterHook, AuthGuard, AuthModule, AuthService, BEFORE_HOOK_KEY, BeforeHook, HOOK_KEY, Hook, Optional, Public, Session };
export type { AuthHookContext, AuthModuleAsyncOptions, UserSession };