> ## Documentation Index
> Fetch the complete documentation index at: https://docs.learnway.xyz/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication & Security

> Comprehensive guide to authentication mechanisms, JWT token lifecycle, multi-factor auth (TOTP), wallet PINs, and security policies.

# Authentication & Security Architecture

LearnWay provides an enterprise-grade authentication system accommodating password-based login, passwordless OTP verification, social identity federation (Google & Apple), 2FA/TOTP, and biometric/wallet PIN authorization.

***

## Authentication Methods

```mermaid theme={null}
flowchart TD
    User([User / Mobile Client]) --> Choice{Auth Method}
    Choice -->|Email + Password| PassAuth[Password Flow]
    Choice -->|Social OAuth| SocialAuth[Google / Apple Provider]
    Choice -->|Passwordless OTP| OtpAuth[Email OTP Flow]
    
    PassAuth --> TOTPCheck{2FA Enabled?}
    TOTPCheck -->|Yes| TOTPVerify[TOTP Verification Step]
    TOTPCheck -->|No| IssueToken[Generate JWT Tokens]
    
    TOTPVerify --> IssueToken
    SocialAuth --> IssueToken
    OtpAuth --> IssueToken
    
    IssueToken --> TokenPair[Access Token + Refresh Token]
```

### 1. Password Registration & Login

* Password hashing with **Bcrypt** utilizing unique salts and server-side peppers.
* Account lockout mechanism after multiple consecutive failed attempts.
* Password reset flow using timed, single-use JWT reset tokens delivered via Resend.

### 2. Social Authentication

* Supported providers: **Google** and **Apple**.
* Client sends third-party identity token; backend validates signature and retrieves profile details.
* Auto-provisions new user accounts or links existing profiles seamlessly.

### 3. Passwordless OTP

* Secure 6-digit OTP generated via cryptographically secure RNG.
* Configurable expiration window (default: 10 minutes) and max retry throttling.

### 4. Two-Factor Authentication (2FA / TOTP)

* Implemented with standard RFC 6238 TOTP (Google Authenticator, Authy).
* Generates QR code and emergency recovery backup codes.
* Required during login if enabled on the account.

***

## Token Lifecycle Management

LearnWay implements a dual-token mechanism:

| Token Type        | Expiry     | Purpose                                                                                                        |
| ----------------- | ---------- | -------------------------------------------------------------------------------------------------------------- |
| **Access Token**  | 15 minutes | Sent in `Authorization: Bearer <token>` for API requests. Contains `userId`, `email`, `role`, and `isPremium`. |
| **Refresh Token** | 30 days    | Exchanged via `/api/v2/auth/refresh` to issue a fresh access token without re-authenticating.                  |

```http theme={null}
POST /api/v2/auth/refresh
Content-Type: application/json

{
  "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```

***

## Wallet PIN Security

For sensitive financial and blockchain operations (e.g., triggering on-chain transfers, off-ramp cashouts, or viewing private keys), users configure a **6-digit Wallet PIN**:

* Salted and hashed independently from user passwords.
* Throttled attempts with OTP recovery flow (`/api/v2/auth/reset-wallet-pin-otp`).

***

## Role-Based Access Control (RBAC)

The system enforces granular authorization via `@Roles()` decorators and `RolesGuard`:

* `USER`: Regular student account.
* `CREATOR`: Can author courses, questions, and content.
* `MODERATOR`: Can review contests and user submissions.
* `VIEWER`: Read-only administrative access for analytics.
* `ADMIN`: Content and user management access.
* `SUPER_ADMIN`: Full root system privileges and contract execution.
