UNPKG

@wristband/nestjs-auth

Version:

SDK for integrating your NestJS application with Wristband. Handles user authentication, session management, and token management.

74 lines (73 loc) 2.79 kB
import { CanActivate, Type } from '@nestjs/common'; /** * Factory function to create a Wristband authentication guard. * * Creates middleware that validates authentication using configurable strategies (SESSION, JWT, or both). * Supports multi-strategy authentication with automatic fallback between strategies. * * The factory exists to create distinct guard identities for cases where multiple guards with * different configurations are needed in the same application. * * Strategy behavior: * - SESSION: Validates session authentication, optionally checks CSRF, and refreshes expired tokens * - JWT: Validates JWT bearer tokens from Authorization header * - Multi-strategy: Tries strategies in configured order, falls back to next on failure * * NOTE: Token refresh only occurs when both `refreshToken` and `expiresAt` are present in the session. * * @param configKey - The ConfigModule key to read guard configuration from (default: 'wristbandAuthGuard') * @param authToken - The DI token for the WristbandExpressAuthService (default: DEFAULT_AUTH_TOKEN) * @returns A guard class that can be used with @UseGuards() * * @throws {UnauthorizedException} If all configured strategies fail authentication or token refresh fails * @throws {ForbiddenException} If CSRF token validation fails (SESSION strategy only) * @throws {InternalServerErrorException} If an unexpected error occurs during authentication * * @example * ```typescript * // Default guard (reads from 'wristbandAuthGuard' config) * export const WristbandAuthGuard = createWristbandAuthGuard(); * * @Controller('api') * export class MyController { * @Get('protected') * @UseGuards(WristbandAuthGuard) * protectedRoute() { * return { message: 'Authenticated' }; * } * } * ``` * * @example * ```typescript * // Custom guard with different config and service instance * export const AdminAuthGuard = createWristbandAuthGuard('adminAuthGuard', 'ADMIN_AUTH_TOKEN'); * * @Controller('admin') * export class AdminController { * @Get('dashboard') * @UseGuards(AdminAuthGuard) * adminDashboard() { * return { message: 'Admin access granted' }; * } * } * ``` * * @example * ```typescript * // Guard configuration in ConfigModule * import { registerAs } from '@nestjs/config'; * import type { AuthGuardConfig } from '@wristband/nestjs-auth'; * * export const authGuardConfig = registerAs('wristbandAuthGuard', (): AuthGuardConfig => ({ * authStrategies: ['SESSION', 'JWT'], * sessionConfig: { * sessionOptions: { * secrets: process.env.SESSION_SECRET, * enableCsrfProtection: true, * } * } * })); * ``` */ export declare function createWristbandAuthGuard(configKey?: string, authToken?: string): Type<CanActivate>;