Skip to content

๐Ÿ” Authentication, Sessions, & Migration Protocol โ€‹

LuxurAI implements a high-security, multi-layered identity and access management system. It bridges secure browser-based sessions (JWT Cookies) with stateless programmatic API tokens (SDK Keys). The identity architecture provides two secure entryways:

  1. Password Authentication with secure bcrypt hashing and dynamic multi-factor recovery codes.
  2. Passwordless Magic Links delivered via resilient serverless integrations utilizing the Resend API.

๐Ÿ—๏ธ Technical Identity Flow โ€‹

The system manages user identity using JSON Web Tokens (JWT) signed using the standard HS256 cryptographic algorithm.

mermaid
graph TD
    %% User Entrances
    BrowserUser[Web Browser Client] -->|Submit Credentials| PasswordAuth[Password login/signup]
    BrowserUser -->|Request Access Link| MagicLink[Magic Link Request]
    SDKDeveloper[Developer Script / SDK] -->|Custom Header| APIKeyAuth[API Token Access]
    
    %% Auth Processors
    PasswordAuth -->|Validate CryptContext| BcryptGate{Bcrypt Match?}
    BcryptGate -->|Yes| CreateSession[Generate Session ID & JWT]
    BcryptGate -->|No| RejectAuth[Raise 412 Unauthorized]
    
    MagicLink -->|Check Magic Limit| RateLimiter{Rate Limiter}
    RateLimiter -->|Under Limit| ResendEmail[Trigger Resend API Magic Link]
    RateLimiter -->|Rate Limited| BlockMagic[Raise 429 Too Many Requests]
    
    APIKeyAuth -->|SHA-256 Hash check| DBKeyMatch{Active Key in DB?}
    DBKeyMatch -->|Yes| UpdateKeyUsage[Update api_keys Last Used]
    DBKeyMatch -->|No| RejectKey[Raise 401 Invalid Key]
    
    %% Session Creation
    CreateSession -->|Set Secure Cookie| SetCookie[Set luxurai_session Cookie]
    UpdateKeyUsage --> AllowAccess[Grant API Gateway Access]
    SetCookie --> AllowAccess

๐Ÿ’พ Database Schemas & Session Storage โ€‹

Identity tables are hosted in SQLite (swapping to PostgreSQL in production environments). The SQL table schema is declared inside backend/auth/auth.py and strictly enforces foreign key integrity:

1. Users Table Schema (users) โ€‹

sql
CREATE TABLE IF NOT EXISTS users (
    id                     TEXT PRIMARY KEY,
    email                  TEXT UNIQUE NOT NULL,
    provider               TEXT NOT NULL DEFAULT 'email', -- 'email' or 'google'
    google_id              TEXT,
    name                   TEXT,
    password_hash          TEXT,                          -- Bcrypt hash string
    recovery_email         TEXT,                          -- Secondary email for multi-factor reset
    is_blocked             INTEGER NOT NULL DEFAULT 0,    -- Absolute firewall ban
    created_at             TEXT NOT NULL,
    last_login             TEXT,
    training_consent       INTEGER NOT NULL DEFAULT 1,    -- opt-in/opt-out for model training
    contributed_gemini_key TEXT,                          -- shared community keys
    key_share_enabled      INTEGER NOT NULL DEFAULT 0,
    coder_key              TEXT                           -- Hexadecimal 512-bit programmatic key
);

2. Live Sessions Table (sessions) โ€‹

Tracks active sessions to ensure stateless JWT tokens can be revoked instantly from the server:

sql
CREATE TABLE IF NOT EXISTS sessions (
    session_id  TEXT PRIMARY KEY,
    user_id     TEXT NOT NULL REFERENCES users(id),
    ip          TEXT,
    user_agent  TEXT,
    created_at  TEXT NOT NULL,
    last_seen   TEXT NOT NULL,
    revoked     INTEGER NOT NULL DEFAULT 0
);

๐Ÿ›ก๏ธ Authentication Endpoints โ€‹

All actions are mapped under the root router namespace.

1. Login with Password โ€‹

  • Endpoint: POST /api/auth/login
  • Payload:
    json
    {
      "email": "[email protected]",
      "password": "super_secure_user_pass_129"
    }
  • Success Response (200 OK): Sets a secure cookie in the client browser:
    http
    Set-Cookie: luxurai_session=<jwt_token>; Domain=.luxurai.in; Path=/; Max-Age=2592000; HttpOnly; Secure; SameSite=Lax
    Returns user metadata:
    json
    {
      "success": true,
      "token": "eyJhbGciOiJIUzI1NiIsIn...",
      "user": {
        "id": "usr_c90K8h21d",
        "email": "[email protected]",
        "name": "LuxurAI Dev"
      }
    }
  • Older User Migration Edge Case: If the account exists but has no password hash registered (e.g. users who signed up under legacy passwordless-only versions), the endpoint returns a migration response, guiding the user to sign in using their magic link and complete password migration:
    json
    {
      "error": "old_user_migration",
      "message": "Please use Magic Link to upgrade your account."
    }

2. Magic Link Request (Passwordless Entry) โ€‹

Sends a premium, high-fashion stylized magic link email to the user's primary email.

  • Endpoint: POST /api/auth/magic-link
  • Payload:
    json
    {
      "email": "[email protected]",
      "desktop": false,
      "training_consent": true
    }
  • Rate Limits: To prevent DDoS attacks on the Resend API subscription, the backend enforces a rate limiter:
    • Hourly Limit: 3 magic link emails per hour per email.
    • Daily Limit: 10 magic link emails per day per email.
  • Resend Template Configuration: The email template is custom-written in modern inline HTML containing elegant typography and custom branding. In local development (DEV mode), the Resend API request is bypassed, and the login link is printed directly to the server terminal:
    bash
    [DEV] RESEND_API_KEY not set โ€” magic link for [email protected]: https://luxurai.in/pages/auth.html?_token=xyz

3. Password Recovery & 2FA Setup โ€‹

If a password is forgotten, users can trigger an automated multi-factor reset code routed to their recovery email address:

  • Endpoint: POST /api/auth/forgot-password
  • Payload:
    json
    {
      "email": "[email protected]"
    }
  • Processing:
    1. The server fetches the user record and retrieves recovery_email.
    2. Generates a cryptographically secure 6-digit code.
    3. Inserts the code into the recovery_codes table with a strict 10-minute expiry window.
    4. Dispatches the code to the recovery email via Resend.
    5. Returns a redacted email hint to the UI (e.g., "sec***@gmail.com").

๐Ÿ”‘ Session Validation Middleware โ€‹

The FastAPI application mounts a global activity-tracking middleware inside backend/main.py. This middleware inspects incoming HTTP requests for the Authorization header or session cookie:

python
# Real-world backend middleware implementation:
@app.middleware("http")
async def _track_activity(request: Request, call_next):
    try:
        auth_header = request.headers.get("Authorization", "")
        if auth_header.startswith("Bearer "):
            import jwt as _jwt
            payload = _jwt.decode(
                auth_header[7:],
                cfg.JWT_SECRET,
                algorithms=["HS256"],
                options={"verify_exp": False}, # decode without expiry to prevent thread locking
            )
            uid = payload.get("sub")
            if uid:
                session_mgr.touch(str(uid)) # Touch RAM session manager
    except Exception:
        pass
    return await call_next(request)

This active session caching keeps active developers' caches warm in memory while automatically evicting inactive sessions on a background loop.

Proprietary & Confidential ยท Powered by LuxurAI