npm package: @hichchi/nest-auth
Description: NestJS authentication extension library that extends @hichchi/nest-core functionality with comprehensive JWT tokens, Google OAuth, local authentication, role-based access control, permission guards, user caching, encryption services, token management, and
Author: Waruna Udayanga
Latest version: 0.0.12

<!--suppress ALL -->

<div align="center">

# 🔐 @hichchi/nest-auth

## Description

**NestJS authentication extension library that extends @hichchi/nest-core functionality with comprehensive JWT tokens, Google OAuth, local authentication, role-based access control, permission guards, user caching, encryption services, token management, and enterprise-grade security features - cannot be used independently, requires nest-core as foundation**

[![npm version](https://img.shields.io/npm/v/@hichchi/nest-auth?style=flat&color=blue)](https://www.npmjs.com/package/@hichchi/nest-auth)
[![npm downloads](https://img.shields.io/npm/dm/@hichchi/nest-auth?style=flat&color=green)](https://www.npmjs.com/package/@hichchi/nest-auth)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/hichchidev/hichchi/blob/main/LICENSE)
[![NestJS](https://img.shields.io/badge/nestjs-11.1.3-red.svg)](https://nestjs.com/)

_Part of the [Hichchi](https://github.com/hichchidev/hichchi) ecosystem - A powerful, scalable application built with Nx workspace_

[📚 Jump to Documentation](#-api-documentation)

</div>

---

## 📋 Table of Contents

- [📦 Installation](#-installation)
- [⚡ Quick Start](#-quick-start)
- [📋 Prerequisites](#-prerequisites)
- [🌟 Overview](#-overview)
- [✨ Features](#-features)
- [🚀 Usage](#-usage)
- [🔧 Configuration Reference](#-configuration-reference)
- [🔧 Development](#-development)
- [📖 API Documentation](#-api-documentation)

---

## 📦 Installation

```bash
npm install @hichchi/nest-core @hichchi/nest-auth
```

## ⚡ Quick Start

Get up and running with authentication in just a few minutes! This guide will walk you through setting up a complete authentication system with JWT tokens, user management, and secure endpoints.

#### 1. Create a NestJS service implementing `IUserService`

First, you need to create a service that handles user operations in your database. This service must implement the `IUserService` interface to work with the authentication module.

**_NOTE:_** All available methods can be found in the [IUserService](#iuserservice) interface documentation.

```typescript
import { Injectable } from "@nestjs/common";
import { GoogleProfile, IUserService } from "@hichchi/nest-auth";
import { AuthProvider, User } from "@hichchi/nest-connector/auth";
import { EntityId } from "@hichchi/nest-connector/crud";

@Injectable()
export class UserService implements IUserService {
  /**
   * Find user by email address (required for email-based authentication)
   */
  getUserByEmail(email: string): Promise<(User & { email: string }) | null> {
    // Implement your database query logic here
    // Example: return await this.userRepository.findOne({ where: { email } });
  }

  /**
   * Find user by username (required for username-based authentication)
   */
  getUserByUsername(
    username: string,
  ): Promise<(User & { username: string }) | null> {
    // Implement your database query logic here
    // Example: return this.userRepository.findOne({ where: { username } });
  }

  /**
   * Find user by ID (required for token validation and user profile operations)
   */
  getUserById(id: EntityId): Promise<User | null> {
    // Implement your database query logic here
    // Example: return this.userRepository.findOne({ where: { id } });
  }

  /**
   * Create new user during registration (supports both local and OAuth registration)
   */
  signUpUser(
    userDto: Partial<User>,
    signUpType: AuthProvider,
    profile?: GoogleProfile,
  ): Promise<User | null> {
    // Implement user creation logic here
    // Handle password hashing for local registration
    // Handle OAuth profile data for social registration
    // Example: return this.createUser(userDto, signUpType, profile);
  }

  /**
   * Update existing user information (required for profile updates)
   */
  updateUserById(
    id: EntityId,
    userDto: Partial<User>,
    updatedBy: User,
  ): Promise<User | null> {
    // Implement user update logic here
    // Example: return this.userRepository.update(id, userDto);
  }
}
```

#### 2. Create and export your user module

Create a module that provides your user service and makes it available for dependency injection.

```typescript
import { Module } from "@nestjs/common";
import { UserService } from "./services";

@Module({
  providers: [UserService],
  // Export the service so it can be used by the auth module
  exports: [UserService],
})
export class UserModule {}
```

#### 3. Register the authentication module in your `app.module.ts`

Configure the authentication module by providing your user service and setting up authentication options.

**_NOTE:_** All available configuration options can be found in the [AuthOptions](#authoptions) interface documentation.

```typescript
import { Module } from "@nestjs/common";
import { AuthField, AuthMethod } from "@hichchi/nest-connector/auth";
import { HichchiAuthModule } from "@hichchi/nest-auth";
import { UserModule } from "./user/user.module";

@Module({
  imports: [
    // Register the authentication module with your user service
    HichchiAuthModule.register(
      {
        imports: [UserModule], // Import your user module
        useExisting: UserService, // Use your existing user service
      },
      {
        // Optional: Redis configuration for token caching and session management
        redis: {
          host: "localhost",
          port: 6379,
          prefix: "nest-auth", // Prefix for Redis keys
        },
        // JWT token configuration
        jwt: {
          secret: "your-super-secret-jwt-key-here", // Use a strong secret in production
          expiresIn: 86400, // Access token expires in 24 hours (in seconds)
          refreshSecret: "your-super-secret-refresh-key-here", // Use a different secret for refresh tokens
          refreshExpiresIn: 604800, // Refresh token expires in 7 days (in seconds)
        },
        authMethod: AuthMethod.JWT, // Use JWT-based authentication
        authField: AuthField.EMAIL, // Authenticate users by email address
        validationExceptionFactory: true, // Enable detailed validation error messages
      },
    ),
  ],
})
export class AppModule {}
```

#### 4. Start using the authentication endpoints

Once configured, your application will automatically have the following authentication endpoints available under `/auth`:

**Authentication Endpoints:**

- `POST /auth/sign-up` - Register a new user account
- `POST /auth/sign-in` - Login with email/username and password
- `POST /auth/sign-out` - Logout and invalidate tokens
- `POST /auth/refresh-token` - Refresh access tokens using refresh token
- `POST /auth/get-auth-response` - Get authentication response from an existing token
- `GET /auth/me` - Get current user profile (requires authentication)
- `POST /auth/change-password` - Change user password (requires authentication)
- `POST /auth/request-password-reset` - Request password reset
- `POST /auth/reset-password-verify` - Verify password reset token/code
- `POST /auth/reset-password` - Reset password using reset token
- `POST /auth/resend-email-verification` - Send verification email again
- `POST /auth/verify-email` - Verify email address
- `GET /auth/google-sign-in` - Initiate Google OAuth login (if configured)
- `GET /auth/google-callback` - Google OAuth callback endpoint

**_NOTE:_** All available endpoints are also available from `AuthEndpoint` enum of the [@hichchi/nest-connector](https://www.npmjs.com/package/@hichchi/nest-connector) package

**Example Usage:**

```bash
# Register a new user
curl -X POST http://localhost:3000/auth/sign-up \
  -H "Content-Type: application/json" \
  -d '{"email": "user@example.com", "password": "securePassword123"}'

# Login
curl -X POST http://localhost:3000/auth/sign-in \
  -H "Content-Type: application/json" \
  -d '{"email": "user@example.com", "password": "securePassword123"}'

# Access protected profile endpoint (include JWT token in Authorization header)
curl -X GET http://localhost:3000/auth/me \
  -H "Authorization: Bearer YOUR_JWT_TOKEN_HERE"
```

Your authentication system is now ready to use! 🎉

## 📋 Prerequisites

Before installing @hichchi/nest-auth, ensure you have:

### Required Dependencies

- **Node.js**: >= 18.0.0
- **NestJS**: >= 11.0.0
- **TypeScript**: >= 5.6.0

### Peer Dependencies

```bash
npm install @nestjs/common @nestjs/core @nestjs/jwt @nestjs/passport
npm install passport passport-local passport-jwt
npm install bcrypt jsonwebtoken
```

### Internal Dependencies

This package depends on:

```bash
npm install @hichchi/nest-connector @hichchi/nest-core @hichchi/utils
```

### Optional Dependencies

For enhanced features:

```bash
# For Google OAuth
npm install passport-google-oauth20
```

### Database Requirements

- A user entity/model in your database
- User service that implements basic CRUD operations
- Fields for email/username and password storage

## 🌟 Overview

🎯 **Your complete authentication toolkit** for NestJS applications. From JWT tokens to Google OAuth, from Redis caching to encryption services - everything you need to secure your application with enterprise-grade authentication features.

## ✨ Features

### 🚀 Ready-to-Use Authentication Endpoints

- 📝 **User Registration** - Complete sign-up flow with email verification
- 🔐 **User Login/Logout** - Secure authentication with JWT tokens
- 🔄 **Token Refresh** - Automatic token renewal for seamless user experience
- 👤 **User Profile Management** - Get current user info and update profiles
- 🔑 **Password Management** - Change password and reset password functionality
- ✉️ **Email Verification** - Built-in email verification system
- 🌐 **Google OAuth Integration** - Social login with Google authentication

### 🔐 Authentication Strategies

- 🔑 **JWT Authentication** - Secure token-based authentication with customizable options
- 👤 **Local Authentication** - Traditional username/password authentication
- 🌐 **Google OAuth 2.0** - Social authentication integration

### 🛡️ Route Protection

- 🔒 **JWT Auth Guard** - Protect your routes with JWT token validation
- 👮 **Role-Based Access Control** - Restrict access based on user roles with tenant-aware user typing support
- 🎫 **Permission-Based Access Control** - Fine-grained permission system
- 🌍 **Google Auth Guard** - Protect routes with Google OAuth

### 🎯 Helpful Decorators

- 👤 **@CurrentUser** - Get the authenticated user in your controllers
- 🏷️ **@Roles** - Define required roles for route access
- 🎫 **@Permission** - Define required permissions for route access
- 📋 **@AuthInfo** - Access authentication metadata

### 🔧 Configuration Options

- 🔧 **Flexible Module Setup** - Easy configuration with your existing user service
- ⚡ **Redis Caching** - Optional Redis integration for improved performance
- 🔒 **Security Settings** - Customizable JWT options, password requirements
- 🌐 **Multi-tenant Support** - tenant-based authentication with normalized tenant slug claims in JWT payloads
- 🔌 **WebSocket Support** - Real-time authentication for WebSocket connections

## 🚀 Usage

### Using Guards

#### `JwtAuthGuard`

This guard is used to authenticate requests using JWT tokens. It validates JWT tokens from either the Authorization header (Bearer token) or cookies, depending on your authentication method configuration. The guard also supports automatic token refresh when using cookie-based authentication.

```typescript
import { JwtAuthGuard, CurrentUser, AuthUser } from "@hichchi/nest-auth";
import { UseGuards, Post, Get, Body } from "@nestjs/common";

// In a controller - protect routes that require authentication
@UseGuards(JwtAuthGuard)
@Post()
create(@Body() dto: CreateUserDto, @CurrentUser() user: AuthUser): Promise<User | null> {
  return this.userService.save(dto);
}

// Get current user profile
@UseGuards(JwtAuthGuard)
@Get('profile')
getProfile(@CurrentUser() user: AuthUser): AuthUser {
  return user;
}
```

#### `LocalAuthGuard`

This guard is used to authenticate users with username/password credentials (local authentication). It validates that the required credentials (email/username and password) are provided in the request body before proceeding with authentication using the local strategy.

Usually used with `@CurrentUser()` decorator - the `LocalAuthGuard` handles the authentication part and returns the authenticated user to the request, and the decorator is used to access the authenticated user from the request.

```typescript
import {
  AuthUser,
  CurrentUser,
  LocalAuthGuard,
  SignInDto
} from "@hichchi/nest-auth";
import { AuthEndpoint, AuthResponse } from "@hichchi/nest-connector/auth";
import { HttpSuccessStatus } from "@hichchi/nest-connector";
import { Post, HttpCode, UseGuards, Body } from "@nestjs/common";

// In a controller - for sign-in endpoint
@Post(AuthEndpoint.SIGN_IN)
@HttpCode(HttpSuccessStatus.OK)
@UseGuards(LocalAuthGuard)
signIn(
  @CurrentUser() authUser: AuthUser,
  @Body() signInDto: SignInDto,
): Promise<AuthResponse> {
  return this.authService.signIn(authUser, signInDto);
}
```

#### `GoogleAuthGuard`

This guard is used to authenticate users with Google OAuth 2.0. It handles the OAuth authentication flow, validates that Google authentication is properly configured, and manages authentication callbacks from Google's OAuth service. Requires Google OAuth configuration in your auth options.

```typescript
import { GoogleAuthGuard } from "@hichchi/nest-auth";
import { UseGuards, Get, Query } from "@nestjs/common";

// Initiate Google OAuth authentication
@UseGuards(GoogleAuthGuard)
@Get('google-sign-in')
googleSignIn(@Query('redirectUrl') redirectUrl: string): void {
  // This route initiates Google OAuth authentication
  // User will be redirected to Google's OAuth consent screen
}

// Handle Google OAuth callback
@UseGuards(GoogleAuthGuard)
@Get('google-callback')
googleCallback(): void {
  // This route handles the callback from Google after authentication
  // The guard processes the OAuth response and authenticates the user
}
```

### Using Decorators

#### `@CurrentUser`

This decorator is used to extract the authenticated user information from the request context. It removes sensitive information like password and provides access to user details in controller methods. Requires authentication guard to be applied to the route.

```typescript
import { CurrentUser, AuthUser, JwtAuthGuard } from "@hichchi/nest-auth";
import { UseGuards, Get, Post, Body } from "@nestjs/common";

// Get current authenticated user
@UseGuards(JwtAuthGuard)
@Get('profile')
getProfile(@CurrentUser() user: AuthUser): AuthUser {
  return user; // Password is automatically removed
}

// Use current user in business logic
@UseGuards(JwtAuthGuard)
@Post('users')
createUser(@Body() dto: CreateUserDto, @CurrentUser() user: AuthUser): Promise<User> {
  return this.userService.save({ ...dto, createdBy: user.id });
}
```

#### `@Roles`

This decorator is used to define required roles for route access. Works with role-based access control to restrict endpoints based on user roles.

```typescript
import { Roles, RoleGuard, JwtAuthGuard } from "@hichchi/nest-auth";
import { UseGuards, Delete, Put, Param, Body } from "@nestjs/common";

// Require admin role
@UseGuards(JwtAuthGuard, RoleGuard)
@Roles('admin')
@Delete(':id')
deleteUser(@Param('id') id: string): Promise<void> {
  return this.userService.delete(id);
}

// Require multiple roles (user must have at least one)
@UseGuards(JwtAuthGuard, RoleGuard)
@Roles('admin', 'moderator')
@Patch(':id')
updateUser(@Param('id') id: string, @Body() dto: UpdateUserDto): Promise<User> {
  return this.userService.update(id, dto);
}
```

#### `@Permission`

This decorator is used to define required permissions for route access. Provides fine-grained permission-based access control.

```typescript
import { Permission, PermissionGuard, JwtAuthGuard } from "@hichchi/nest-auth";
import { UseGuards, Get, Delete, Param } from "@nestjs/common";

// Require specific permission
@UseGuards(JwtAuthGuard, PermissionGuard)
@Permission('users:read')
@Get()
getUsers(): Promise<User[]> {
  return this.userService.findAll();
}

// Require multiple permissions
@UseGuards(JwtAuthGuard, PermissionGuard)
@Permission('users:write', 'users:delete')
@Delete(':id')
deleteUser(@Param('id') id: string): Promise<void> {
  return this.userService.delete(id);
}
```

#### `@AuthInfo`

This decorator is used to access authentication metadata and additional information about the current authentication context.

```typescript
import { AuthInfo, JwtAuthGuard } from "@hichchi/nest-auth";
import { UseGuards, Get } from "@nestjs/common";

// Access authentication metadata
@UseGuards(JwtAuthGuard)
@Get('session-info')
getSessionInfo(@AuthInfo() authInfo: any): any {
  return {
    tokenType: authInfo.tokenType,
    issuedAt: authInfo.iat,
    expiresAt: authInfo.exp,
    // Additional auth metadata
  };
}
```

#### `@SocketId`

This decorator is used to extract the socket ID from the authenticated user's token data in the request. It provides easy access to the socket ID within controller methods for WebSocket-related functionality. Requires authentication guard to be applied to the route.

```typescript
import { SocketId, JwtAuthGuard } from "@hichchi/nest-auth";
import { UseGuards, Get, Post, Body } from "@nestjs/common";

// Get socket ID for WebSocket operations
@UseGuards(JwtAuthGuard)
@Get('socket-info')
getSocketInfo(@SocketId() socketId: string): any {
  return {
    socketId,
    message: 'Socket ID retrieved successfully'
  };
}

// Use socket ID in business logic
@UseGuards(JwtAuthGuard)
@Post('users/:id/update')
updateUserWithSocket(@Param('id') id: string, @Body() dto: UpdateUserDto, @SocketId() socketId: string): Promise<User> {
  return this.userService.update(id, { ...dto, socketId });
}
```

#### `@Tenant`

This decorator is used to extract the tenant identifier from the incoming request headers using the configured tenant header key. It provides a simple way to access tenant context in controller methods for multi-tenant routing and business logic.

```typescript
import { Tenant, JwtAuthGuard } from "@hichchi/nest-auth";
import { UseGuards, Get, Post, Body } from "@nestjs/common";

// Read tenant context from request headers
@UseGuards(JwtAuthGuard)
@Get('tenant-context')
getTenantContext(@Tenant() tenant: TenantSlug): any {
  return {
    tenant,
    message: 'Tenant resolved successfully'
  };
}

// Use tenant in service operations
@UseGuards(JwtAuthGuard)
@Post('users')
createTenantUser(@Body() dto: CreateUserDto, @Tenant() tenant: TenantSlug): Promise<User> {
  return this.userService.createForTenant(tenant, dto);
}
```

### Using Extractors

#### `cookieExtractor`

This extractor function is used to extract JWT access tokens from request cookies. It's primarily used internally by the authentication system when using cookie-based authentication, but can also be used in custom authentication strategies.

```typescript
import { cookieExtractor } from "@hichchi/nest-auth";
import { ExtractJwt } from "passport-jwt";
import { Request } from "express";

// Use with passport-jwt ExtractJwt.fromExtractors
const jwtOptions = {
  jwtFromRequest: ExtractJwt.fromExtractors([cookieExtractor]),
  secretOrKey: "your-secret-key",
};

// Manual usage to extract token from request
function extractTokenFromCookies(request: Request): string | null {
  return cookieExtractor(request);
}

// Example in a custom strategy
@Injectable()
export class CustomJwtStrategy extends PassportStrategy(
  Strategy,
  "custom-jwt",
) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromExtractors([
        cookieExtractor, // Extract from cookies first
        ExtractJwt.fromAuthHeaderAsBearerToken(), // Fallback to Authorization header
      ]),
      secretOrKey: process.env.JWT_SECRET,
    });
  }
}
```

### Using Utilities

#### Configuration Validation Functions

These utility functions help validate authentication configuration during module setup to ensure all required options are properly configured.

##### `validateRedisOptions`

Validates Redis connection options to ensure either a URL or host is provided for establishing a connection.

```typescript
import { validateRedisOptions } from "@hichchi/nest-auth";
import { RedisOptions } from "@hichchi/nest-core";

// Validate Redis configuration before using
const redisConfig: RedisOptions = {
  host: "localhost",
  port: 6379,
  prefix: "auth-cache",
};

try {
  validateRedisOptions(redisConfig);
  console.log("Redis configuration is valid");
} catch (error) {
  console.error("Invalid Redis configuration:", error.message);
}

// Example with URL-based configuration
const redisUrlConfig: RedisOptions = {
  url: "redis://localhost:6379",
};

validateRedisOptions(redisUrlConfig); // Will pass validation
```

##### `validateJwtOptions`

Validates JWT configuration options to ensure all required secrets and expiration times are provided.

```typescript
import { validateJwtOptions } from "@hichchi/nest-auth";
import { JwtOptions } from "@hichchi/nest-auth";

// Validate JWT configuration
const jwtConfig: JwtOptions = {
  secret: "your-access-token-secret",
  expiresIn: 3600, // 1 hour
  refreshSecret: "your-refresh-token-secret",
  refreshExpiresIn: 604800, // 7 days
};

try {
  validateJwtOptions(jwtConfig);
  console.log("JWT configuration is valid");
} catch (error) {
  console.error("Invalid JWT configuration:", error.message);
}

// Example usage in module configuration
@Module({
  imports: [
    HichchiAuthModule.register(
      {
        /* user service config */
      },
      {
        jwt: jwtConfig, // This will be validated internally
        // other auth options...
      },
    ),
  ],
})
export class AppModule {}
```

##### `validateUserServiceProvider`

Validates that a user service implements all required methods based on the authentication configuration.

```typescript
import { validateUserServiceProvider } from "@hichchi/nest-auth";
import { IUserService, AuthOptions } from "@hichchi/nest-auth";
import { AuthField } from "@hichchi/nest-connector/auth";

// Example user service implementation
@Injectable()
export class UserService implements IUserService {
  async getUserByEmail(email: string) {
    /* implementation */
  }
  async getUserByUsername(username: string) {
    /* implementation */
  }
  async getUserById(id: string) {
    /* implementation */
  }
  async signUpUser(userDto: any) {
    /* implementation */
  }
  async updateUserById(id: string, userDto: any) {
    /* implementation */
  }
}

// Validate the user service against auth configuration
const authOptions: AuthOptions = {
  authField: AuthField.EMAIL,
  jwt: {
    /* jwt config */
  },
  googleAuth: {
    /* google config */
  },
};

const userService = new UserService();

try {
  validateUserServiceProvider(userService, authOptions);
  console.log("User service implements all required methods");
} catch (error) {
  console.error("User service validation failed:", error.message);
}
```

#### User Management Functions

##### `generateAuthUser`

Generates an AuthUser object from cached user data and access token, combining user information with session details.

```typescript
import { generateAuthUser } from "@hichchi/nest-auth";
import { CacheUser, AuthUser } from "@hichchi/nest-auth";

// Example cached user data
const cacheUser: CacheUser = {
  id: "user-123",
  firstName: "John",
  lastName: "Doe",
  email: "john.doe@example.com",
  roles: ["user"],
  sessions: [
    {
      sessionId: "session-456",
      accessToken: "jwt-access-token-here",
      refreshToken: "jwt-refresh-token-here",
    },
  ],
};

// Generate AuthUser from cache and token
try {
  const authUser: AuthUser = generateAuthUser(
    cacheUser,
    "jwt-access-token-here",
  );

  console.log("Generated AuthUser:", {
    id: authUser.id,
    fullName: authUser.fullName, // 'John Doe' - automatically generated
    email: authUser.email,
    sessionId: authUser.sessionId,
    accessToken: authUser.accessToken,
    refreshToken: authUser.refreshToken,
  });
} catch (error) {
  console.error("Failed to generate AuthUser:", error.message);
}

// Example usage in a custom authentication service
@Injectable()
export class CustomAuthService {
  constructor(private cacheService: UserCacheService) {}

  async getAuthenticatedUser(accessToken: string): Promise<AuthUser> {
    // Get user from cache (implementation depends on your cache strategy)
    const cacheUser = await this.cacheService.getUserByToken(accessToken);

    if (!cacheUser) {
      throw new UnauthorizedException("User not found in cache");
    }

    // Generate AuthUser with session information
    return generateAuthUser(cacheUser, accessToken);
  }
}
```

## 🔧 Configuration Reference

### Complete Configuration Options

```typescript
// JWT authentication configuration options
interface JwtOptions {
  /** Secret key used to sign JWT access tokens */
  secret: string;
  /** Expiration time for access tokens in seconds */
  expiresIn: number;
  /** Secret key used to sign JWT refresh tokens */
  refreshSecret: string;
  /** Expiration time for refresh tokens in seconds */
  refreshExpiresIn: number;
}

// Google OAuth authentication configuration options
interface GoogleAuthOptions {
  /** Google OAuth client ID from Google Developer Console */
  clientId: string;
  /** Google OAuth client secret from Google Developer Console */
  clientSecret: string;
}

// Cookie configuration options
interface CookiesOptions {
  /** Secret key used for signing cookies */
  secret?: string;
  /** Controls how cookies are sent with cross-site requests */
  sameSite?: boolean | "lax" | "strict" | "none";
  /** Whether cookies should only be sent over HTTPS */
  secure?: boolean;
}

// Main authentication configuration options
interface AuthOptions {
  /**
   * Whether the application is running in production mode
   * @default false
   */
  isProd?: boolean;

  /**
   * Redis configuration for caching user sessions
   * When provided, user sessions will be stored in Redis
   */
  redis?: RedisOptions;

  /**
   * Secret key used for encrypting user sessions in cache
   * Required when using Redis caching with sensitive user data
   */
  sessionSecret?: string;

  /**
   * JWT configuration options (Required)
   */
  jwt: JwtOptions;

  /**
   * Google OAuth configuration options
   * When provided, enables Google OAuth authentication
   */
  googleAuth?: GoogleAuthOptions;

  /**
   * Cookie configuration options
   * Used when authMethod is set to AuthMethod.COOKIE
   */
  cookies?: CookiesOptions;

  /**
   * Whether to verify user email before allowing authentication
   * @default false
   */
  checkEmailVerified?: boolean;

  /**
   * URL to redirect to after email verification
   * Required when checkEmailVerified is true
   */
  emailVerifyRedirect?: string;

  /**
   * Password reset token expiration time in seconds
   * @default 3600 (1 hour)
   */
  passwordResetExp?: number;

  /**
   * Authentication method (JWT, Cookie, etc.)
   * @default AuthMethod.JWT
   */
  authMethod?: AuthMethod;

  /**
   * Field used for authentication (email, username, etc.)
   * @default AuthField.EMAIL
   */
  authField?: AuthField | string;

  /**
   * Custom DTO class for sign-up requests
   */
  signUpDto?: typeof SignUpDto;

  /**
   * Custom DTO class for user views
   */
  viewDto?: Type<ViewUserDto>;

  /**
   * Custom validation exception factory
   * @default false
   */
  validationExceptionFactory?:
    | boolean
    | ((errors: ValidationError[]) => HttpException);

  /**
   * Whether to disable sign-up functionality
   * @default false
   */
  disableSignUp?: boolean;

  /**
   * List of allowed domains for redirect URLs
   * Used to prevent open redirect vulnerabilities
   */
  allowedRedirectDomains?: string[];
}
```

### Default Configuration

```typescript
const defaultConfig: Partial<AuthOptions> = {
  isProd: false,
  checkEmailVerified: false,
  passwordResetExp: 3600, // 1 hour
  authMethod: AuthMethod.JWT,
  authField: AuthField.EMAIL,
  disableSignUp: false,
  validationExceptionFactory: false,
};
```

## 🔧 Development

### Building

```bash
nx build nest-auth
```

Compile and bundle the authentication module for production use.

### Testing

```bash
nx test nest-auth
```

Run comprehensive unit tests powered by [Jest](https://jestjs.io).

---

<div align="center">

**Made with ❤️ by [Hichchi Dev](https://github.com/hichchidev)**

[![Hichchi Ecosystem](https://img.shields.io/badge/🏠_Hichchi_Ecosystem-blue)](https://github.com/hichchidev/hichchi)
[![Report Bug](https://img.shields.io/badge/🐛_Report_Bug-red)](https://github.com/hichchidev/hichchi/issues)
[![Request Feature](https://img.shields.io/badge/✨_Request_Feature-green)](https://github.com/hichchidev/hichchi/issues)

_Empowering secure applications with enterprise-grade authentication, JWT tokens, OAuth integration, and role-based access control_

</div>

---

# 📖 API Documentation

Complete technical reference for all classes, interfaces, methods, and types in this library.

**Auto-generated by TypeDoc** - Browse through detailed API references, code examples, and implementation guides below.

<!-- TypeDoc generated documentation will be appended below this point -->

---

## 📋 API Table of Contents

- [Classes](#classes)
  - [AuthController](#authcontroller)
  - [AuthService](#authservice)
  - [EmailVerifyDto](#emailverifydto)
  - [GetAuthResponseDto](#getauthresponsedto)
  - [GoogleAuthGuard](#googleauthguard-1)
  - [GoogleStrategy](#googlestrategy)
  - [HichchiAuthModule](#hichchiauthmodule)
  - [JwtAuthGuard](#jwtauthguard-1)
  - [JwtStrategy](#jwtstrategy)
  - [JwtTokenService](#jwttokenservice)
  - [LocalAuthGuard](#localauthguard-1)
  - [LocalStrategy](#localstrategy)
  - [OverrideSignUpDtoPipe](#overridesignupdtopipe)
  - [PermissionGuard](#permissionguard)
  - [RefreshTokenDto](#refreshtokendto)
  - [RequestResetDto](#requestresetdto)
  - [ResendEmailVerifyDto](#resendemailverifydto)
  - [ResetPasswordDto](#resetpassworddto)
  - [ResetPasswordTokenVerifyDto](#resetpasswordtokenverifydto)
  - [RoleGuard](#roleguard)
  - [SignInDto](#signindto)
  - [SignUpDto](#signupdto)
  - [UpdatePasswordDto](#updatepassworddto)
  - [UserCacheService](#usercacheservice)
  - [ViewUserDto](#viewuserdto)
- [Functions](#functions)
  - [AuthInfo()](#authinfo-1)
  - [cookieExtractor()](#cookieextractor-1)
  - [CurrentTenant()](#currenttenant)
  - [CurrentTenantId()](#currenttenantid)
  - [CurrentUser()](#currentuser-1)
  - [Permission()](#permission-1)
  - [Roles()](#roles-1)
  - [SocketId()](#socketid-1)
- [Interfaces](#interfaces)
  - [AuthOptions](#authoptions)
  - [AuthUser](#authuser)
  - [CacheUser](#cacheuser)
  - [CookiesOptions](#cookiesoptions)
  - [CurrentTenantIdOptions](#currenttenantidoptions)
  - [GoogleAuthOptions](#googleauthoptions)
  - [IJwtPayload](#ijwtpayload)
  - [IUserService](#iuserservice)
  - [JwtOptions](#jwtoptions)
  - [UserExtra](#userextra)
  - [UserServiceActions](#userserviceactions)
  - [UserServiceEvents](#userserviceevents)
  - [UserServiceExistingProvider](#userserviceexistingprovider)
  - [UserServiceFactoryProvider](#userservicefactoryprovider)
- [Type Aliases](#type-aliases)
  - [UserServiceProvider](#userserviceprovider)
- [Variables](#variables)
  - [ACCESS_TOKEN_COOKIE_NAME](#access_token_cookie_name)
  - [AUTH_OPTIONS](#auth_options)
  - [EMAIL_KEY](#email_key)
  - [PERMISSION_KEY](#permission_key)
  - [REFRESH_TOKEN_COOKIE_NAME](#refresh_token_cookie_name)
  - [ROLES_KEY](#roles_key)
  - [USER_SERVICE](#user_service)
  - [USERNAME_KEY](#username_key)

## Classes

### AuthController

Defined in: [libs/nest-auth/src/controllers/auth.controller.ts:72](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-auth/src/controllers/auth.controller.ts#L72)

Authentication controller that handles all authentication-related endpoints.

This controller provides endpoints for user sign up, authentication, password management,
email verification, and social authentication.

The default endpoint path is 'auth' but can be customized by extending this class:

#### Example

```typescript
@Controller("custom-auth")
export class CustomAuthController extends AuthController {
  // Override existing methods or add new ones

  @Get("custom-endpoint")
  async customEndpoint() {
    return "Custom endpoint";
  }
}
```

#### See

- Endpoint.AUTH - The default endpoint path constant used for this controller.
- Endpoint - Contains all available endpoints for this module.

#### Constructors

##### Constructor

```ts
new AuthController(options, authService): AuthController;
```

Defined in: [libs/nest-auth/src/controllers/auth.controller.ts:83](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-auth/src/controllers/auth.controller.ts#L83)

Creates an instance of AuthController.

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`options`

</td>
<td>

[`AuthOptions`](#authoptions)

</td>
<td>

The authentication options injected from `AUTH_OPTIONS` token

</td>
</tr>
<tr>
<td>

`authService`

</td>
<td>

[`AuthService`](#authservice)

</td>
<td>

The authentication service

</td>
</tr>
</tbody>
</table>

###### Returns

[`AuthController`](#authcontroller)

###### See

- [AUTH_OPTIONS](#auth_options) Token used to inject authentication options
- [AuthOptions](#authoptions) Interface defining authentication configuration
- [AuthService](#authservice) Service handling authentication logic

#### Methods

##### changePassword()

```ts
changePassword(
   request,
   authUser,
   updatePasswordDto,
tenant?): Promise<User<string, string, TenantSlug>>;
```

Defined in: [libs/nest-auth/src/controllers/auth.controller.ts:485](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-auth/src/controllers/auth.controller.ts#L485)

Changes the password for the currently authenticated user.

This endpoint allows an authenticated user to change their password.
It requires both the current password and the new password.

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`request`

</td>
<td>

`Request`

</td>
<td>

The Express request object

</td>
</tr>
<tr>
<td>

`authUser`

</td>
<td>

[`AuthUser`](#authuser)

</td>
<td>

The authenticated user information (provided by JwtAuthGuard)

</td>
</tr>
<tr>
<td>

`updatePasswordDto`

</td>
<td>

[`UpdatePasswordDto`](#updatepassworddto)

</td>
<td>

DTO containing the current and new passwords

</td>
</tr>
<tr>
<td>

`tenant?`

</td>
<td>

`TenantSlug`

</td>
<td>

The tenant slug (optional)

</td>
</tr>
</tbody>
</table>

###### Returns

`Promise`<`User`<`string`, `string`, `TenantSlug`>>

The updated user information

###### Example

```typescript
// Client-side example
const response = await fetch("/auth/change-password", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: "Bearer your-jwt-token",
  },
  body: JSON.stringify({
    currentPassword: "current-password",
    newPassword: "new-password",
  }),
});
```

```json
// result:
{
  "id": "123e4567-e89b-12d3-a456-426614174000",
  "email": "user@example.com",
  "firstName": "John",
  "lastName": "Doe",
  "isVerified": true,
  "signUpType": "local"
}
```

###### See

- AuthEndpoint.CHANGE_PASSWORD - The specific endpoint path segment for changing user passwords.
- AuthEndpoint - Enum containing all authentication-specific endpoint paths.
- Endpoint.AUTH - The default endpoint path constant used for this controller.

##### getAuthResponse()

```ts
getAuthResponse(
   request,
   response,
   getAuthResponseDto,
tenant?): Promise<AuthResponse>;
```

Defined in: [libs/nest-auth/src/controllers/auth.controller.ts:339](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-auth/src/controllers/auth.controller.ts#L339)

Gets a complete authentication response using an existing access token.

This endpoint allows clients to retrieve a complete authentication response
using a previously issued JWT access token. It verifies the token,
retrieves the associated user information, generates new tokens,
and returns comprehensive authentication data.

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`request`

</td>
<td>

`Request`

</td>
<td>

The Express request object

</td>
</tr>
<tr>
<td>

`response`

</td>
<td>

`Response`

</td>
<td>

The Express response object for setting cookies

</td>
</tr>
<tr>
<td>

`getAuthResponseDto`

</td>
<td>

[`GetAuthResponseDto`](#getauthresponsedto)

</td>
<td>

DTO containing the JWT access token

</td>
</tr>
<tr>
<td>

`tenant?`

</td>
<td>

`TenantSlug`

</td>
<td>

The tenant slug (optional)

</td>
</tr>
</tbody>
</table>

###### Returns

`Promise`<`AuthResponse`>

Authentication response containing user info and tokens

###### Example

```typescript
// Client-side example - using a previously obtained JWT token
const response = await fetch("/auth/get-auth-response", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    accessToken: "previously-issued-jwt-token",
  }),
});
const authData = await response.json();
```

```json
// Result:
{
  "user": {
    "id": "123e4567-e89b-12d3-a456-426614174000",
    "email": "user@example.com",
    "firstName": "John",
    "lastName": "Doe",
    "isVerified": true,
    "signUpType": "google"
  },
  "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "accessTokenExpiresOn": "2025-06-24T15:12:45.123Z",
  "refreshTokenExpiresOn": "2025-07-24T10:12:45.123Z",
  "sessionId": "sess_abc123"
}
```

###### See

- AuthEndpoint.GET_AUTH_RESPONSE - The specific endpoint path segment for retrieving authentication data.
- AuthEndpoint - Enum containing all authentication-specific endpoint paths.
- Endpoint.AUTH - The default endpoint path constant used for this controller.

##### getCurrentUser()

```ts
getCurrentUser(
   request,
   authUser,
tenant?): Promise<User<string, string, TenantSlug> | null>;
```

Defined in: [libs/nest-auth/src/controllers/auth.controller.ts:431](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-auth/src/controllers/auth.controller.ts#L431)

Retrieves the currently authenticated user's information.

This endpoint returns the user information for the currently authenticated user.
It requires a valid JWT token and is protected by the JwtAuthGuard.

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`request`

</td>
<td>

`Request`

</td>
<td>

The Express request object

</td>
</tr>
<tr>
<td>

`authUser`

</td>
<td>

[`AuthUser`](#authuser)

</td>
<td>

The authenticated user information (provided by JwtAuthGuard)

</td>
</tr>
<tr>
<td>

`tenant?`

</td>
<td>

`TenantSlug`

</td>
<td>

The tenant slug (optional)

</td>
</tr>
</tbody>
</table>

###### Returns

`Promise`<`User`<`string`, `string`, `TenantSlug`> | `null`>

The current user's information or null if not found

###### Example

```typescript
// Client-side example
const response = await fetch("/auth/me", {
  method: "GET",
  headers: {
    Authorization: "Bearer your-jwt-token",
  },
});
const user = await response.json();
```

```json
// result:
{
  "id": "123e4567-e89b-12d3-a456-426614174000",
  "email": "user@example.com",
  "firstName": "John",
  "lastName": "Doe",
  "isVerified": true,
  "signUpType": "local"
}
```

###### See

- AuthEndpoint.ME - The specific endpoint path segment for retrieving current user information.
- AuthEndpoint - Enum containing all authentication-specific endpoint paths.
- Endpoint.AUTH - The default endpoint path constant used for this controller.

##### googleCallback()

```ts
googleCallback(
   response,
   authUser,
   state): void;
```

Defined in: [libs/nest-auth/src/controllers/auth.controller.ts:276](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-auth/src/controllers/auth.controller.ts#L276)

Handles the callback from Google OAuth authentication.

This endpoint is called by Google after successful authentication.
It extracts the redirect URL from the state parameter and redirects the user
to that URL with the access token as a query parameter.

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`response`

</td>
<td>

`Response`

</td>
<td>

The Express response object for redirection

</td>
</tr>
<tr>
<td>

`authUser`

</td>
<td>

[`AuthUser`](#authuser)

</td>
<td>

The authenticated user information (provided by GoogleAuthGuard)

</td>
</tr>
<tr>
<td>

`state`

</td>
<td>

`string`

</td>
<td>

JSON string containing the redirectUrl

</td>
</tr>
</tbody>
</table>

###### Returns

`void`

This method doesn't return any content as it redirects to the client application

###### Throws

If there's an error processing the callback

###### Example

```typescript
// This endpoint is not called directly from client code
// It's called by Google's OAuth service after user authenticates
// The flow typically is:
// 1. User clicks "Sign In with Google" link (pointing to googleSignIn endpoint)
// 2. User authenticates on Google's site
// 3. Google redirects to this callback URL
// 4. This method redirects to the original application with the token
```

###### See

- AuthEndpoint.GOOGLE_CALLBACK - The specific endpoint path segment for Google OAuth callback processing.
- AuthEndpoint - Enum containing all authentication-specific endpoint paths.
- Endpoint.AUTH - The default endpoint path constant used for this controller.

##### googleSignIn()

```ts
googleSignIn(_query): Promise<void>;
```

Defined in: [libs/nest-auth/src/controllers/auth.controller.ts:239](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-auth/src/controllers/auth.controller.ts#L239)

Initiates Google OAuth sign-in flow.

This endpoint redirects the user to Google's authentication page.
The redirectUrl query parameter is used to determine where to redirect after successful authentication.

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`_query`

</td>
<td>

`GoogleAuthRequestQuery`

</td>
<td>

The query parameters from the request

</td>
</tr>
</tbody>
</table>

###### Returns

`Promise`<`void`>

This method doesn't return any content as it redirects to Google

###### Example

```typescript
// Client-side example - typically used as a link in your frontend
<a href="/auth/google-sign-in?redirectUrl=http://your-app.com/dashboard">
    Sign in with Google
</a>
```

Note: Recommended approach is to use a browser popup or new tab to call this API instead of a full page redirect.
This allows smoother handling of the authentication flow and makes it easier to capture the callback response,
especially in single-page applications (SPAs) or when working with cross-origin redirects.

###### See

- AuthEndpoint.GOOGLE_SIGN_IN - The specific endpoint path segment for initiating Google OAuth flow.
- AuthEndpoint - Enum containing all authentication-specific endpoint paths.
- Endpoint.AUTH - The default endpoint path constant used for this controller.

##### refreshTokens()

```ts
refreshTokens(
   request,
   refreshTokenDto,
   response,
tenant?): Promise<TokenResponse>;
```

Defined in: [libs/nest-auth/src/controllers/auth.controller.ts:380](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-auth/src/controllers/auth.controller.ts#L380)

Refreshes the authentication tokens using a refresh token.

This endpoint allows clients to obtain new access and refresh tokens
when their current access token expires, without requiring the user to log in again.

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`request`

</td>
<td>

`Request`

</td>
<td>

The Express request object

</td>
</tr>
<tr>
<td>

`refreshTokenDto`

</td>
<td>

[`RefreshTokenDto`](#refreshtokendto)

</td>
<td>

DTO containing the refresh token

</td>
</tr>
<tr>
<td>

`response`

</td>
<td>

`Response`

</td>
<td>

The Express response object for setting cookies

</td>
</tr>
<tr>
<td>

`tenant?`

</td>
<td>

`TenantSlug`

</td>
<td>

The tenant slug (optional)

</td>
</tr>
</tbody>
</table>

###### Returns

`Promise`<`TokenResponse`>

New access and refresh tokens

###### Example

```typescript
// Client-side example
const response = await fetch("/auth/refresh-token", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    refreshToken: "your-refresh-token",
  }),
});
const tokens = await response.json();
// tokens contains new accessToken and refreshToken
```

###### See

- AuthEndpoint.REFRESH_TOKEN - The specific endpoint path segment for token refreshing.
- AuthEndpoint - Enum containing all authentication-specific endpoint paths.
- Endpoint.AUTH - The default endpoint path constant used for this controller.

##### requestPasswordReset()

```ts
requestPasswordReset(
   request,
   requestResetDto,
tenant?): Promise<SuccessResponse>;
```

Defined in: [libs/nest-auth/src/controllers/auth.controller.ts:629](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-auth/src/controllers/auth.controller.ts#L629)

Initiates the password reset process for a user.

This endpoint allows users to request a password reset by providing their email address.
If the email exists in the system, a password reset link will be sent to that email.

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`request`

</td>
<td>

`Request`

</td>
<td>

The Express request object

</td>
</tr>
<tr>
<td>

`requestResetDto`

</td>
<td>

[`RequestResetDto`](#requestresetdto)

</td>
<td>

DTO containing the email address

</td>
</tr>
<tr>
<td>

`tenant?`

</td>
<td>

`TenantSlug`

</td>
<td>

The tenant slug (optional)

</td>
</tr>
</tbody>
</table>

###### Returns

`Promise`<`SuccessResponse`>

Success response indicating the reset email was sent

###### Example

```typescript
// Client-side example
const response = await fetch("/auth/request-password-reset", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    email: "user@example.com",
  }),
});
const result = await response.json();
```

```json
// result:
{
  "statusCode": 200,
  "code": "AUTH_200_PASSWORD_RESET_EMAIL_SENT",
  "message": "Password reset email sent successfully"
}
```

###### See

- AuthEndpoint.REQUEST_PASSWORD_RESET - The specific endpoint path segment for requesting password resets.
- AuthEndpoint - Enum containing all authentication-specific endpoint paths.
- Endpoint.AUTH - The default endpoint path constant used for this controller.

##### resendEmailVerification()

```ts
resendEmailVerification(
   request,
   resendEmailVerifyDto,
tenant?): Promise<SuccessResponse>;
```

Defined in: [libs/nest-auth/src/controllers/auth.controller.ts:533](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-auth/src/controllers/auth.controller.ts#L533)

Resends the email verification link to the user.

This endpoint allows users to request a new email verification link
if they didn't receive the original one or if it expired.

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`request`

</td>
<td>

`Request`

</td>
<td>

The Express request object

</td>
</tr>
<tr>
<td>

`resendEmailVerifyDto`

</td>
<td>

[`ResendEmailVerifyDto`](#resendemailverifydto)

</td>
<td>

DTO containing the email address

</td>
</tr>
<tr>
<td>

`tenant?`

</td>
<td>

`TenantSlug`

</td>
<td>

The tenant slug (optional)

</td>
</tr>
</tbody>
</table>

###### Returns

`Promise`<`SuccessResponse`>

Success response indicating the email was sent

###### Example

```typescript
// Client-side example
const response = await fetch("/auth/resend-email-verification", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    email: "user@example.com",
  }),
});
const result = await response.json();
```

```json
// result:
{
  "statusCode": 200,
  "code": "AUTH_200_EMAIL_VERIFICATION_SENT",
  "message": "Verification email sent successfully"
}
```

###### See

- AuthEndpoint.RESEND_EMAIL_VERIFICATION - The specific endpoint path segment for resending verification emails.
- AuthEndpoint - Enum containing all authentication-specific endpoint paths.
- Endpoint.AUTH - The default endpoint path constant used for this controller.

##### resetPassword()

```ts
resetPassword(
   request,
   resetPasswordDto,
tenant?): Promise<SuccessResponse>;
```

Defined in: [libs/nest-auth/src/controllers/auth.controller.ts:722](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-auth/src/controllers/auth.controller.ts#L722)

Resets a user's password using a valid reset token.

This endpoint allows users to set a new password after verifying their reset token.
It should be called after the token has been verified using the verifyResetPasswordToken endpoint.

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`request`

</td>
<td>

`Request`

</td>
<td>

The Express request object

</td>
</tr>
<tr>
<td>

`resetPasswordDto`

</td>
<td>

[`ResetPasswordDto`](#resetpassworddto)

</td>
<td>

DTO containing the reset token and new password

</td>
</tr>
<tr>
<td>

`tenant?`

</td>
<td>

`TenantSlug`

</td>
<td>

The tenant slug (optional)

</td>
</tr>
</tbody>
</table>

###### Returns

`Promise`<`SuccessResponse`>

Success response indicating the password was reset

###### Example

```typescript
// Client-side example
const response = await fetch("/auth/reset-password", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    token: "reset-token-from-email",
    password: "new-password",
  }),
});
const result = await response.json();
```

```json
// result:
{
  "statusCode": 200,
  "code": "AUTH_200_PASSWORD_RESET_SUCCESS",
  "message": "Password reset successfully"
}
```

###### See

- AuthEndpoint.RESET_PASSWORD - The specific endpoint path segment for setting a new password after reset.
- AuthEndpoint - Enum containing all authentication-specific endpoint paths.
- Endpoint.AUTH - The default endpoint path constant used for this controller.

##### signIn()

```ts
signIn(
   request,
   authUser,
   _signInDto,
   response,
tenant?): Promise<AuthResponse>;
```

Defined in: [libs/nest-auth/src/controllers/auth.controller.ts:201](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-auth/src/controllers/auth.controller.ts#L201)

Authenticates a user with email/username and password.

This endpoint handles user sign in using local authentication strategy.
It sets authentication cookies and returns user information with tokens.

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`request`

</td>
<td>

`Request`

</td>
<td>

The Express request object

</td>
</tr>
<tr>
<td>

`authUser`

</td>
<td>

[`AuthUser`](#authuser)

</td>
<td>

The authenticated user information (provided by LocalAuthGuard)

</td>
</tr>
<tr>
<td>

`_signInDto`

</td>
<td>

[`SignInDto`](#signindto)

</td>
<td>

The sign in credentials (not used directly as LocalAuthGuard handles validation)

</td>
</tr>
<tr>
<td>

`response`

</td>
<td>

`Response`

</td>
<td>

The Express response object for setting cookies

</td>
</tr>
<tr>
<td>

`tenant?`

</td>
<td>

`TenantSlug`

</td>
<td>

The tenant slug (optional)

</td>
</tr>
</tbody>
</table>

###### Returns

`Promise`<`AuthResponse`>

Authentication response containing user info and tokens

###### Example

```typescript
// Client-side example
const response = await fetch("/auth/sign-in", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    email: "user@example.com",
    password: "password123",
  }),
});
const authData = await response.json();
```

```json
// Result:
{
  "user": {
    "id": "123e4567-e89b-12d3-a456-426614174000",
    "email": "user@example.com",
    "firstName": "John",
    "lastName": "Doe",
    "isVerified": true,
    "signUpType": "local"
  },
  "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "accessTokenExpiresOn": "2025-06-24T15:12:45.123Z",
  "refreshTokenExpiresOn": "2025-07-24T10:12:45.123Z",
  "sessionId": "sess_abc123"
}
```

###### See

- AuthEndpoint.SIGN_IN - The specific endpoint path segment for user authentication.
- AuthEndpoint - Enum containing all authentication-specific endpoint paths.
- Endpoint.AUTH - The default endpoint path constant used for this controller.

##### signOut()

```ts
signOut(
   request,
   authUser,
response): Promise<SuccessResponse>;
```

Defined in: [libs/nest-auth/src/controllers/auth.controller.ts:774](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-auth/src/controllers/auth.controller.ts#L774)

Signs out the currently authenticated user.

This endpoint invalidates the user's authentication tokens and clears authentication cookies.
It requires a valid JWT token and is protected by the JwtAuthGuard.

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`request`

</td>
<td>

`Request`

</td>
<td>

The Express request object

</td>
</tr>
<tr>
<td>

`authUser`

</td>
<td>

[`AuthUser`](#authuser)

</td>
<td>

The authenticated user information (provided by JwtAuthGuard)

</td>
</tr>
<tr>
<td>

`response`

</td>
<td>

`Response`

</td>
<td>

The Express response object for clearing cookies

</td>
</tr>
</tbody>
</table>

###### Returns

`Promise`<`SuccessResponse`>

Success response indicating the user was signed out

###### Example

```typescript
// Client-side example
const response = await fetch("/auth/sign-out", {
  method: "POST",
  headers: {
    Authorization: "Bearer your-jwt-token",
  },
});
const result = await response.json();

// After this, the client should clear any stored tokens and redirect to the sign in page
localStorage.removeItem("accessToken");
localStorage.removeItem("refreshToken");
window.location.href = "/sign-in";
```

```json
// result
{
  "statusCode": HttpSuccessStatus.OK,
  "code": AuthSuccessResponseCode.AUTH_200_SIGNED_OUT,
  "message": "Signed out successfully",
}
```

###### See

- AuthEndpoint.SIGN_OUT - The specific endpoint path segment for user logout and token invalidation.
- AuthEndpoint - Enum containing all authentication-specific endpoint paths.
- Endpoint.AUTH - The default endpoint path constant used for this controller.

##### signUp()

```ts
signUp(
   request,
   dto,
tenant?): Promise<User<string, string, TenantSlug>>;
```

Defined in: [libs/nest-auth/src/controllers/auth.controller.ts:137](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-auth/src/controllers/auth.controller.ts#L137)

Sign up a new user with the provided sign-up data.

This endpoint creates a new user account with the provided sign up data.
If sign up is disabled in the auth options, it will throw a ForbiddenException.

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`request`

</td>
<td>

`Request`

</td>
<td>

The Express request object

</td>
</tr>
<tr>
<td>

`dto`

</td>
<td>

`SignUpBody`

</td>
<td>

The sign-up data transfer object containing user sign up information

</td>
</tr>
<tr>
<td>

`tenant?`

</td>
<td>

`TenantSlug`

</td>
<td>

The tenant slug (optional)

</td>
</tr>
</tbody>
</table>

###### Returns

`Promise`<`User`<`string`, `string`, `TenantSlug`>>

The newly created user

###### Throws

If sign up is disabled

###### Example

```typescript
// Client-side example
const response = await fetch("/auth/sign-up", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    email: "user@example.com",
    password: "password123",
    firstName: "John",
    lastName: "Doe",
  }),
});
const user = await response.json();
```

```json
// Result:
{
  "id": "123e4567-e89b-12d3-a456-426614174000",
  "email": "user@example.com",
  "firstName": "John",
  "lastName": "Doe",
  "isVerified": true,
  "signUpType": "local",
  "createdAt": "2025-06-24T10:12:45.123Z",
  "updatedAt": "2025-06-24T11:30:15.456Z"
}
```

###### See

- AuthEndpoint.SIGN_UP - The specific endpoint path segment for user registration.
- AuthEndpoint - Enum containing all authentication-specific endpoint paths.
- Endpoint.AUTH - The default endpoint path constant used for this controller.

##### verifyEmail()

```ts
verifyEmail(
   request,
   response,
   emailVerifyDto,
tenant?): Promise<void>;
```

Defined in: [libs/nest-auth/src/controllers/auth.controller.ts:573](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-auth/src/controllers/auth.controller.ts#L573)

Verifies a user's email address using the verification token.

This endpoint is accessed via a link sent to the user's email.
It verifies the token and redirects the user to a configured URL
with a query parameter indicating whether verification was successful.

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`request`

</td>
<td>

`Request`

</td>
<td>

The Express request object

</td>
</tr>
<tr>
<td>

`response`

</td>
<td>

`Response`

</td>
<td>

The Express response object for redirection

</td>
</tr>
<tr>
<td>

`emailVerifyDto`

</td>
<td>

[`EmailVerifyDto`](#emailverifydto)

</td>
<td>

DTO containing the verification token

</td>
</tr>
<tr>
<td>

`tenant?`

</td>
<td>

`TenantSlug`

</td>
<td>

The tenant slug (optional)

</td>
</tr>
</tbody>
</table>

###### Returns

`Promise`<`void`>

This method doesn't return any content as it redirects to the configured URL

###### Example

```html
This endpoint is typically accessed via a link in an email:

<a href="https://your-api.com/auth/verify-email?token=verification-token">
  Verify Email
</a>

The user will be redirected to the configured URL:
https://your-app.com/email-verification?verified=true
```

###### See

- AuthEndpoint.VERIFY_EMAIL - The specific endpoint path segment for email verification processing.
- AuthEndpoint - Enum containing all authentication-specific endpoint paths.
- Endpoint.AUTH - The default endpoint path constant used for this controller.

##### verifyResetPasswordToken()

```ts
verifyResetPasswordToken(request, verifyDto): Promise<SuccessResponse>;
```

Defined in: [libs/nest-auth/src/controllers/auth.controller.ts:675](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-auth/src/controllers/auth.controller.ts#L675)

Verifies a password reset token.

This endpoint allows clients to verify if a password reset token is valid
before showing the password reset form to the user.

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`request`

</td>
<td>

`Request`

</td>
<td>

The Express request object

</td>
</tr>
<tr>
<td>

`verifyDto`

</td>
<td>

[`ResetPasswordTokenVerifyDto`](#resetpasswordtokenverifydto)

</td>
<td>

DTO containing the reset token

</td>
</tr>
</tbody>
</table>

###### Returns

`Promise`<`SuccessResponse`>

Success response indicating if the token is valid

###### Example

```typescript
// Client-side example
const response = await fetch("/auth/reset-password-verify", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    token: "reset-token-from-email",
  }),
});
const result = await response.json();
```

```json
// result:
{
  "statusCode": 200,
  "code": "AUTH_200_PASSWORD_RESET_TOKEN_VALID",
  "message": "Password reset token is valid"
}
```

###### See

- AuthEndpoint.RESET_PASSWORD_VERIFY - The specific endpoint path segment for verifying password reset tokens.
- AuthEndpoint - Enum containing all authentication-specific endpoint paths.
- Endpoint.AUTH - The default endpoint path constant used for this controller.

#### Properties

<table>
<thead>
<tr>
<th>Property</th>
<th>Modifier</th>
<th>Type</th>
<th>Description</th>
<th>Defined in</th>
</tr>
</thead>
<tbody>
<tr>
<td>

<a id="property-authservice"></a> `authService`

</td>
<td>

`readonly`

</td>
<td>

[`AuthService`](#authservice)

</td>
<td>

The authentication service

</td>
<td>

[libs/nest-auth/src/controllers/auth.controller.ts:85](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-auth/src/controllers/auth.controller.ts#L85)

</td>
</tr>
</tbody>
</table>

---

### AuthService

Defined in: [libs/nest-auth/src/services/auth.service.ts:108](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-auth/src/services/auth.service.ts#L108)

Core authentication service that provides comprehensive identity management functionality.

This service is responsible for handling all authentication-related operations within the application.
It works alongside the AuthController to provide a complete authentication solution. The service
delegates many operations to specialized services like JwtTokenService for token management,
UserCacheService for session management, and TokenVerifyService for verification tokens.

Key features include:

- User sign up and sign in with email/username and password
- JWT token generation, validation, and refresh
- Password management (change, reset, verify)
- Email verification workflow
- Social authentication (Google OAuth)
- Session management with multi-device support
- Token-based and cookie-based authentication modes

The service is designed to be flexible and configurable through the AuthOptions injection token,
allowing applications to customize authentication behaviors. It also integrates with a user service
provided by the application through the USER_SERVICE injection token, which handles user data storage.

Security features include:

- Secure password hashing with bcrypt
- Cryptographically secure token generation
- Token expiration and refresh mechanisms
- Protection against common authentication vulnerabilities

#### Example

```typescript
// In a controller
@Controller("auth")
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Post("sign-up")
  async signUp(@Req() request: Request, @Body() signUpDto: SignUpDto) {
    return this.authService.signUp(request, signUpDto);
  }
}
```

#### See

- [AuthController](#authcontroller) The controller that exposes authentication endpoints using this service
- [JwtTokenService](#jwttokenservice) Service responsible for JWT token operations
- [UserCacheService](#usercacheservice) Service that manages user session caching
- TokenVerifyService Service that handles verification tokens
- [AuthOptions](#authoptions) Configuration options for authentication behavior
- [IUserService](#iuserservice) Interface that user services must implement

#### Constructors

##### Constructor

```ts
new AuthService(
   options,
   userService,
   jwtTokenService,
   cacheService,
   tokenVerifyService): AuthService;
```

Defined in: [libs/nest-auth/src/services/auth.service.ts:118](https://github.com/hichchidev/hichchi/blob/451086b0863c82a6952d5ee0c05bf458abaaa227/libs/nest-auth/src/services/auth.service.ts#L118)

Creates an instance of AuthService.

###### Parameters

<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>

`options`

</td>
<td>

[`AuthOptions`](#authoptions)

</td>
<td>

The authentication options injected from `AUTH_OPTIONS` token

</td>
</tr>
<tr>
<td>

`userService`

</td>
<td>

[`IUserService`](#iuserservice)

</td>
<td>

The user service injected from `USER_SERVICE` token

</td>
</tr>
<tr>
<td>

`jwtTokenService`

</td>
<td>

[`JwtTokenService`](#jwttokenservice)

</td>
<td>

The JWT token service for token operations

</td>
</tr>
<tr>
<td>

`cacheService`

</td>
<td>

[`UserCacheService`](#usercacheservice)

</td>
<td>

The user cache service for storing user sessions

</td>
</tr>
<tr>
<td>

`tokenVerifyService`

</td>
<td>

`TokenVerifyService`

</td>
<td>

The token verification service for email and password reset tokens

</td>
</tr>
</tbody>
</table>

###### Returns

[`AuthService`](#authservice)

#### Methods

##### authenticate()

```ts
authenticate(
   request,
   username,
   password,
tenant?): Promise<AuthUser>;
```

Defined