# @hsuite/auth - Authentication & User Management Module

> 🔐 **Comprehensive NestJS authentication module providing unified Web2 & Web3 authentication, user management, and API key authentication**

A robust, enterprise-grade authentication module that seamlessly integrates traditional username/password authentication with cutting-edge Web3 wallet-based authentication, complete user management, and API key authentication system, designed specifically for the HSuite ecosystem.

***

## Table of Contents

* [Quick Start](#quick-start)
* [Architecture](#architecture)
* [API Reference](#api-reference)
* [Guides](#guides)
* [Examples](#examples)
* [Integration](#integration)

***

## Quick Start

### Installation

```bash
npm install @hsuite/auth
```

### Basic Setup

```typescript
import { AuthModule } from '@hsuite/auth';

@Module({
  imports: [
    AuthModule.forRootAsync({
      useFactory: () => ({
        commonOptions: {
          jwt: { secret: 'your-secret', signOptions: { expiresIn: '24h' } },
          passport: IAuth.IConfiguration.IPassportStrategy.JWT
        },
        web2Options: { confirmation_required: true },
        web3Options: { tokenGateOptions: {} }
      })
    })
  ]
})
export class AppModule {}
```

### Protect Your Routes

```typescript
@UseGuards(JwtAuthGuard)
@Get('protected')
getProtected(@Request() req) {
  return { user: req.user };
}
```

***

## Architecture

### Core Components

#### 🛡️ **Guards**

* **`JwtAuthGuard`** - JWT-based route protection
* **`RedisAuthGuard`** - Redis session authentication
* **`ConfirmedAuthGuard`** - Email confirmation requirement
* **`ApiKeyAuthGuard`** - API key authentication guard

#### 🌐 **Strategies**

* **`JwtStrategy`** - Passport JWT strategy implementation
* **`RedisStrategy`** - Redis-based session strategy
* **`Web3Strategy`** - Blockchain wallet authentication
* **`ApiKeyStrategy`** - Header-based API key validation

#### 🔧 **Services**

* **`AuthService`** - Core authentication logic
* **`UsersService`** - User management operations
* **`ApiKeyService`** - API key validation
* **`AuthController`** - REST API endpoints

#### 👥 **User Management**

* **`UsersModule`** - Complete user management module
* **`UsersService`** - User CRUD operations and business logic
* **`UserModelService`** - Database operations with Mongoose
* **`User Entity`** - Mongoose schema and TypeScript types

#### 🔑 **API Key Authentication**

* **`ApiKeyModule`** - API key authentication module
* **`ApiKeyService`** - API key validation and management
* **`ApiKeyAuthGuard`** - Route protection with API keys
* **`ApiKeyStrategy`** - Passport strategy for API keys

### Module Structure

```
src/
├── users/           # User management module
│   ├── entities/    # Mongoose schemas
│   ├── models/      # Database operations
│   ├── users.service.ts
│   └── users.module.ts
├── api-key/         # API key authentication module
│   ├── guards/      # API key guard
│   ├── strategies/  # API key strategy
│   ├── api-key.service.ts
│   └── api-key.module.ts
├── guards/          # Route protection guards
├── strategies/      # Passport authentication strategies  
├── interfaces/      # TypeScript interfaces
├── serializers/     # Session serialization
├── web2/           # Traditional auth (username/password)
├── web3/           # Blockchain auth (wallet-based)
├── redis/          # Redis session management
├── auth.module.ts   # Main module configuration
├── auth.service.ts  # Core service implementation
└── auth.controller.ts # HTTP endpoints
```

***

## API Reference

### AuthModule

#### Static Methods

**`forRootAsync(options: AuthModuleAsyncOptions): DynamicModule`**

Configures the authentication module with async dependency injection.

```typescript
interface AuthModuleAsyncOptions {
  imports?: any[];
  useFactory?: (...args: any[]) => Promise<IAuth.IConfiguration.IAuthentication>;
  inject?: any[];
  config?: {
    passport: IAuth.IConfiguration.IPassportStrategy;
    module: 'web2' | 'web3';
    options: IAuth.IConfiguration.IOptions;
  };
}
```

### AuthService

#### Core Methods

**`validateUser(username: string, password: string): Promise<any>`**

* Validates user credentials for Web2 authentication

**`login(user: any): Promise<{ access_token: string }>`**

* Generates JWT token for authenticated user

**`register(userData: CreateUserDto): Promise<User>`**

* Registers new user with email confirmation

### Guards Reference

#### JwtAuthGuard

```typescript
@UseGuards(JwtAuthGuard)
@Get('jwt-protected')
jwtProtected(@Request() req) {
  return { user: req.user };
}
```

#### RedisAuthGuard

```typescript
@UseGuards(RedisAuthGuard)
@Get('session-protected')
sessionProtected(@Request() req) {
  return { session: req.session };
}
```

#### ConfirmedAuthGuard

```typescript
@UseGuards(JwtAuthGuard, ConfirmedAuthGuard)
@Post('confirmed-only')
confirmedOnly(@Request() req) {
  return { message: 'Email confirmed user only' };
}
```

***

## Guides

### Web2 Authentication Guide

Learn how to implement traditional username/password authentication with email confirmation and 2FA. Configure user registration, login flows, password reset, and session management.

### Web3 Authentication Guide

Implement blockchain wallet-based authentication with signature verification and token gating. Set up wallet connection, signature validation, and decentralized identity management.

### Session Management Guide

Configure Redis-based session management for distributed applications. Implement session storage, expiration policies, and cross-service session sharing.

### Guards & Strategies Guide

Deep dive into authentication guards and Passport strategies. Create custom guards, implement authorization logic, and manage authentication flows.

***

## Examples

### Complete Module Configuration

```typescript
@Module({
  imports: [
    AuthModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        commonOptions: {
          jwt: {
            secret: configService.get('JWT_SECRET'),
            signOptions: { expiresIn: '24h' }
          },
          passport: IAuth.IConfiguration.IPassportStrategy.JWT,
          operator: {
            accountId: configService.get('HEDERA_ACCOUNT_ID'),
            privateKey: configService.get('HEDERA_PRIVATE_KEY')
          },
          appName: configService.get('APP_NAME', 'HSuite')
        },
        web2Options: {
          confirmation_required: true,
          admin_only: false,
          sendMailOptions: {
            confirm: {
              subject: 'Confirm your account',
              template: 'confirmation'
            }
          },
          mailerOptions: {
            transport: {
              host: configService.get('SMTP_HOST'),
              port: configService.get('SMTP_PORT'),
              auth: {
                user: configService.get('SMTP_USER'),
                pass: configService.get('SMTP_PASS')
              }
            }
          },
          twilioOptions: {
            accountSid: configService.get('TWILIO_ACCOUNT_SID'),
            authToken: configService.get('TWILIO_AUTH_TOKEN'),
            serviceSid: configService.get('TWILIO_SERVICE_SID')
          }
        },
        web3Options: {
          tokenGateOptions: {
            requiredTokens: [
              {
                contractAddress: '0x...',
                minimumBalance: 1
              }
            ]
          }
        }
      }),
      inject: [ConfigService]
    })
  ]
})
export class AppModule {}
```

### Multi-Guard Protection

```typescript
@Controller('api')
export class SecureController {
  @UseGuards(JwtAuthGuard, ConfirmedAuthGuard)
  @Get('secure-data')
  getSecureData(@Request() req) {
    return {
      message: 'Access granted to confirmed user',
      user: req.user
    };
  }

  @UseGuards(RedisAuthGuard)
  @Post('session-action')
  sessionAction(@Request() req) {
    return {
      message: 'Session-based action completed',
      sessionId: req.session.id
    };
  }
}
```

***

## Integration

### Required Dependencies

```json
{
  "@hsuite/auth-types": "^2.1.2",
  "@hsuite/client": "^2.1.2",
  "@hsuite/smart-config": "^2.1.1",
  "@hsuite/helpers": "^2.0.8",
  "@hsuite/ipfs": "^2.0.5",
  "@hsuite/mirrors": "^2.0.3",
  "@hsuite/hashgraph-types": "^2.0.3",
  "@hsuite/smart-network-types": "^2.0.0",
  "@hsuite/subscriptions-types": "^2.1.1"
}
```

### Environment Variables

```env
# JWT Configuration
JWT_SECRET=your-secret-key

# Database
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=password
DB_DATABASE=hsuite

# Email Configuration (Web2)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASS=your-app-password

# Twilio Configuration (2FA)
TWILIO_ACCOUNT_SID=ACxxxxx
TWILIO_AUTH_TOKEN=xxxxx
TWILIO_SERVICE_SID=VAxxxxx

# Hedera Configuration (Web3)
HEDERA_ACCOUNT_ID=0.0.123456
HEDERA_PRIVATE_KEY=302e020100300506032b657004220420...
```

### TypeScript Configuration

```json
{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "strict": true
  }
}
```

***

## **📝 Note**: This module requires proper configuration of external services (Redis, PostgreSQL, SMTP, Twilio) for full functionality. See individual guides for detailed setup instructions.

<p align="center">Built with ❤️ by the HSuite Team<br>Copyright © 2025 HSuite. All rights reserved.</p>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.hsuite.network/developers/libs/auth.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
