03 - Login and Broker Login Flow

Overview

OpenAlgo implements a two-phase authentication system:

  1. User Authentication - Username/password login to OpenAlgo

  2. Broker Authentication - OAuth2/TOTP/API-based login to trading broker

This design ensures users first authenticate with OpenAlgo before connecting to their broker account.

Authentication Flow Diagram

Phase 1: User Authentication

Initial Setup Check

On first access, the system checks if any users exist:

Flow:

  • No users → Redirect to /setup for first-time configuration

  • Users exist → Show login page

Login Endpoint

Endpoint: POST /auth/login

Rate Limits:

  • 5 per minute

  • 25 per hour

Password Validation

Passwords must meet these requirements:

Password Hashing

User passwords are hashed using Argon2 with pepper:

Phase 2: Broker Authentication

Broker Types and Auth Methods

OpenAlgo supports 29 brokers with different authentication methods:

Auth Type
Brokers
Flow

OAuth2

Zerodha, Fyers, Flattrade, Dhan, ICICI, Pocketful

Redirect → Callback with code

TOTP

Angel, 5Paisa, Kotak, Shoonya, Firstock, AliceBlue, Motilal

Form + TOTP code

OTP

Definedge

Email/SMS OTP verification

API Key

Dhan (direct), Groww, IndMoney

Direct token auth

XTS

5PaisaXTS, JainamXTS, IIFL, Wisdom

Server-to-server token

OAuth2 Flow (e.g., Zerodha)

TOTP Flow (e.g., Angel)

Broker Callback Handler

The universal callback handler processes all broker authentication:

Authentication Success Handler

After successful broker authentication:

Session Management

Session Data Structure

Session Expiry

Sessions expire daily at 3:30 AM IST to align with market schedules:

Token Storage

Auth Token Encryption

Broker auth tokens are encrypted before database storage:

Database Schema (Auth)

Password Reset Flow

Reset Methods

  1. TOTP-based - Using authenticator app

  2. Email-based - Reset link sent to registered email

Reset Endpoint

Frontend Session Sync

React AuthSync Component

The React frontend synchronizes with Flask session state:

Session Status Endpoint

Logout Flow

Security Considerations

Rate Limiting

Endpoint
Limit

/auth/login

5/min, 25/hour

/{broker}/callback

5/min, 25/hour

/auth/reset-password

15/hour

User Enumeration Prevention

Password reset always returns success regardless of email existence:

CSRF Protection

All POST endpoints (except webhooks) require CSRF tokens:

Key Files Reference

File
Purpose

blueprints/auth.py

User authentication endpoints

blueprints/brlogin.py

Broker callback handlers

utils/auth_utils.py

Auth helpers, password validation

database/auth_db.py

Auth token storage with encryption

database/user_db.py

User model with Argon2 hashing

utils/session.py

Session expiry calculation

frontend/src/stores/authStore.ts

Client-side auth state

frontend/src/components/auth/AuthSync.tsx

Session synchronization

Last updated