# Authentication Flows & Security Mechanisms

This document explains the authentication flows, rate limits, session management, and account lifecycle details.

---

## 1. User Registration & Mobile Verification Flow

```mermaid
sequenceDiagram
    participant App as Mobile App
    participant PHP as PHP Proxy Gateway
    participant API as Node.js API
    participant DB as MySQL DB
    participant SMS as SMS Gateway
    
    App->>PHP: POST /api/register (mobile, details)
    PHP->>API: Proxy register request
    API->>DB: Check if mobile already exists
    alt Mobile already registered
        DB-->>API: Row found
        API-->>App: JSON {status: 0, msg: "User already exists."}
    else Mobile is new
        API->>DB: Insert temporary user record
        API->>API: Generate 6-digit OTP
        API->>DB: Check daily OTP limit (<10/day)
        API->>SMS: Dispatch OTP SMS
        API->>DB: Save OTP record (expiry, ts, attempt)
        API-->>App: JSON {status: 1, msg: "You have registered successfully."}
    end
```

### Mobile Verification Step
1. Upon registration, the user receives an OTP.
2. The user submits the OTP to `/api/register-otp-verification`.
3. The backend updates the database table `kyc` setting `mobile_verified = 1` for the user.

---

## 2. Login & Security PIN Lockout

When a registered user logs in, they first verify their mobile number, then submit their PIN for verification.

### PIN Lockout Logic (Brute Force Protection)
To prevent unauthorized entry, a PIN attempt tracking system is implemented using Redis:
* **Max Attempts:** 5 consecutive failures.
* **Lock Duration:** 15 minutes.

```mermaid
flowchart TD
    Start[User Login with PIN] --> CheckLock{Is user locked out in Redis?}
    CheckLock -->|Yes| Reject[Reject request: Too many attempts. Try in 15 mins.]
    CheckLock -->|No| Query[Verify PIN in DB]
    Query -->|PIN Correct| OK[Clear attempts key in Redis & Log in]
    Query -->|PIN Incorrect| IncAttempts[Increment attempts key in Redis]
    IncAttempts --> CheckCount{Attempts >= 5?}
    CheckCount -->|Yes| Lock[Set lock key in Redis for 15 mins] --> Reject
    CheckCount -->|No| Warn[Show remaining attempts]
```

* **Redis Keys:**
  * Failed attempts tracking: `login:attempts:${mobile}` (TTL: 15 mins)
  * Account lock state: `login:lock:${mobile}` (TTL: 15 mins)

---

## 3. Forgot PIN & OTP Limitations

1. The user requests a PIN reset OTP using `/api/forgot-pin` by submitting their mobile number.
2. If registered, the system generates an OTP and inserts it into the database `otp` table.
3. **Daily OTP Limit:**
   * A user is allowed a maximum of **10 OTP requests per day**.
   * If they request more, the system returns: `"Daily OTP limit reached. Please try again tomorrow."` (Resets daily at midnight).
4. **Resend OTP / 60-Second Rate Limit:**
   * To prevent spamming, requests are rate-limited to **1 OTP per 60 seconds** per user.
   * Controlled atomically in Redis via `otp:lock:${uid}` (TTL: 60s). If hit, returns: `"Please wait 60 seconds before requesting another OTP."`

---

## 4. User Logout

* **Endpoint:** `POST /api/user-logout`
* **Workflow:**
  1. The client sends the `apptoken` representing the active session.
  2. The server updates the user row in the database:
     ```sql
     UPDATE users SET apptoken = NULL, fcmtoken = NULL WHERE uid = ?
     ```
  3. Updating to `NULL` (instead of empty string `''`) prevents database `UNIQUE KEY` constraint collisions (`idx_users_apptoken`) when multiple users log out.

---

## 5. Account Deletion and Cache Invalidation

When a user deletes their account (`POST /api/user-account-delete`), the server performs a complete wipe of the user's relational and cached data:

```mermaid
graph TD
    DeleteCall[Delete Account Request] --> SQL[Database Cleanup]
    DeleteCall --> RedisClean[Redis Cache Invalidation]
    
    subgraph Database Tables Cleared
        SQL --> T1[users & kyc]
        SQL --> T2[user_activity & otp]
        SQL --> T3[positions, orders & watchlists]
        SQL --> T4[notifications & contest_join]
    end
    
    subgraph Redis Keys Evicted
        RedisClean --> R1[user:profile:${uid}]
        RedisClean --> R2[user:kyc:${uid}]
        RedisClean --> R3[apptoken:uid:${apptoken}]
        RedisClean --> R4[cache:trading-terminal:${uid}:*]
        RedisClean --> R5[balance:*:${uid}]
    end
```

This comprehensive cleanup ensures that:
1. No stale token maps remain cached in memory (`apptoken:uid:${apptoken}`).
2. Subsequent client app requests using the old token will return `401 Unauthorized` / `Invalid App Token`, forcing a redirection to the Login screen.
3. User stats, performance dashboard cache, and current ranking are fully removed.
