# Change: Add User Authentication with Auto-Refresh Session Management ## Why The system requires user authentication to identify users in incident chat rooms and maintain audit trails. We integrate with the existing Panjit AD authentication API (https://pj-auth-api.vercel.app/) for credential validation, but manage our own session lifecycle to avoid frequent re-logins. AD API tokens have limited validity, but we want users to stay logged in as long as they actively use the system within a 3-day window. ## What Changes - Implement standalone `auth` module with clear API boundaries for reusability - Implement FastAPI login endpoint that validates credentials via AD API - Generate our own internal session tokens (separate from AD tokens) - Store encrypted passwords securely for auto-refresh capability - Auto-refresh AD tokens before expiry (when user is active, max 3 retry attempts) - Implement 3-day inactivity timeout (last_activity tracking) - Store session data in PostgreSQL with username, display_name, internal_token, ad_token, encrypted_password, token_expires_at, refresh_attempt_count, last_activity - Provide middleware to auto-refresh expired AD tokens on protected routes - Force logout when auto-refresh fails 3 consecutive times (e.g., password changed in AD) - Enable user identity to be used in chat room messages ## Impact - **Affected specs**: `authentication` (new capability) - **Affected code**: - Backend: New standalone `app/modules/auth/` module with: - Routes: `/api/auth/login`, `/api/auth/logout` - Middleware: `AuthMiddleware` for protected routes - Services: `ADAuthService`, `SessionService`, `EncryptionService` - Models: `UserSession` (SQLAlchemy) - Database: New `user_sessions` table with encrypted password storage - Future: This authentication module will be imported by chat room and other features - **Dependencies**: - External: Requires access to `https://pj-auth-api.vercel.app/api/auth/login` - Python packages: `cryptography` for password encryption