This commit introduces major enhancements to Talk2Me: ## Database Integration - PostgreSQL support with SQLAlchemy ORM - Redis integration for caching and real-time analytics - Automated database initialization scripts - Migration support infrastructure ## User Authentication System - JWT-based API authentication - Session-based web authentication - API key authentication for programmatic access - User roles and permissions (admin/user) - Login history and session tracking - Rate limiting per user with customizable limits ## Admin Dashboard - Real-time analytics and monitoring - User management interface (create, edit, delete users) - System health monitoring - Request/error tracking - Language pair usage statistics - Performance metrics visualization ## Key Features - Dual authentication support (token + user accounts) - Graceful fallback for missing services - Non-blocking analytics middleware - Comprehensive error handling - Session management with security features ## Bug Fixes - Fixed rate limiting bypass for admin routes - Added missing email validation method - Improved error handling for missing database tables - Fixed session-based authentication for API endpoints 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
7.1 KiB
Talk2Me Authentication System
This document describes the comprehensive user authentication and authorization system implemented for the Talk2Me application.
Overview
The authentication system provides:
- User account management with roles (admin, user)
- JWT-based API authentication
- Session management for web interface
- API key authentication for programmatic access
- User-specific rate limiting
- Admin dashboard for user management
- Secure password hashing with bcrypt
Features
1. User Management
User Account Model
- Email & Username: Unique identifiers for each user
- Password: Securely hashed using bcrypt
- API Key: Unique key for each user (format:
tk_<random_string>
) - Roles:
admin
oruser
- Account Status: Active, verified, suspended
- Rate Limits: Configurable per-user limits
- Usage Tracking: Tracks requests, translations, transcriptions, and TTS usage
Admin Features
- Create, update, delete users
- Suspend/unsuspend accounts
- Reset passwords
- Manage user permissions
- View login history
- Monitor active sessions
- Bulk operations
2. Authentication Methods
JWT Authentication
- Access tokens (1 hour expiration)
- Refresh tokens (30 days expiration)
- Token blacklisting for revocation
- Secure token storage
API Key Authentication
- Bearer token in
X-API-Key
header - Query parameter fallback:
?api_key=tk_xxx
- Per-key rate limiting
Session Management
- Track active sessions per user
- Session expiration handling
- Multi-device support
- Session revocation
3. Security Features
Password Security
- Bcrypt hashing with salt
- Minimum 8 character requirement
- Password change tracking
- Failed login attempt tracking
- Account lockout after 5 failed attempts (30 minutes)
Rate Limiting
- User-specific limits (per minute/hour/day)
- IP-based fallback for unauthenticated requests
- Admin users get 10x higher limits
- Endpoint-specific overrides
Audit Trail
- Login history with IP and user agent
- Success/failure tracking
- Suspicious activity flagging
- Security event logging
Database Schema
Users Table
- id (UUID, primary key)
- email (unique)
- username (unique)
- password_hash
- api_key (unique)
- role (admin/user)
- is_active, is_verified, is_suspended
- rate limits (per_minute, per_hour, per_day)
- usage stats (total_requests, translations, etc.)
- timestamps (created_at, updated_at, last_login_at)
Login History Table
- id (UUID)
- user_id (foreign key)
- login_at, logout_at
- login_method (password/api_key/jwt)
- success (boolean)
- ip_address, user_agent
- session_id, jwt_jti
User Sessions Table
- id (UUID)
- session_id (unique)
- user_id (foreign key)
- access_token_jti, refresh_token_jti
- created_at, last_active_at, expires_at
- ip_address, user_agent
Revoked Tokens Table
- id (UUID)
- jti (unique, token ID)
- token_type (access/refresh)
- user_id
- revoked_at, expires_at
- reason
API Endpoints
Authentication Endpoints
POST /api/auth/login
Login with username/email and password.
{
"username": "user@example.com",
"password": "password123"
}
Response:
{
"success": true,
"user": { ... },
"tokens": {
"access_token": "eyJ...",
"refresh_token": "eyJ...",
"expires_in": 3600
},
"session_id": "uuid"
}
POST /api/auth/logout
Logout and revoke current token.
POST /api/auth/refresh
Refresh access token using refresh token.
GET /api/auth/profile
Get current user profile.
PUT /api/auth/profile
Update user profile (name, settings).
POST /api/auth/change-password
Change user password.
POST /api/auth/regenerate-api-key
Generate new API key.
Admin User Management
GET /api/auth/admin/users
List all users with filtering and pagination.
POST /api/auth/admin/users
Create new user (admin only).
GET /api/auth/admin/users/:id
Get user details with login history.
PUT /api/auth/admin/users/:id
Update user details.
DELETE /api/auth/admin/users/:id
Delete user account.
POST /api/auth/admin/users/:id/suspend
Suspend user account.
POST /api/auth/admin/users/:id/reset-password
Reset user password.
Usage Examples
Authenticating Requests
Using JWT Token
curl -H "Authorization: Bearer eyJ..." \
https://api.talk2me.app/translate
Using API Key
curl -H "X-API-Key: tk_your_api_key" \
https://api.talk2me.app/translate
Python Client Example
import requests
# Login and get token
response = requests.post('https://api.talk2me.app/api/auth/login', json={
'username': 'user@example.com',
'password': 'password123'
})
tokens = response.json()['tokens']
# Use token for requests
headers = {'Authorization': f"Bearer {tokens['access_token']}"}
translation = requests.post(
'https://api.talk2me.app/translate',
headers=headers,
json={'text': 'Hello', 'target_lang': 'Spanish'}
)
Setup Instructions
1. Install Dependencies
pip install -r requirements.txt
2. Initialize Database
python init_auth_db.py
This will:
- Create all database tables
- Prompt you to create an admin user
- Display the admin's API key
3. Configure Environment
Add to your .env
file:
JWT_SECRET_KEY=your-secret-key-change-in-production
DATABASE_URL=postgresql://user:pass@localhost/talk2me
4. Run Migrations (if needed)
alembic upgrade head
Security Best Practices
- JWT Secret: Use a strong, random secret key in production
- HTTPS Only: Always use HTTPS in production
- Rate Limiting: Configure appropriate limits per user role
- Password Policy: Enforce strong passwords
- Session Timeout: Configure appropriate session durations
- Audit Logging: Monitor login attempts and suspicious activity
- API Key Rotation: Encourage regular API key rotation
- Database Security: Use encrypted connections to database
Admin Dashboard
Access the admin dashboard at /admin/users
(requires admin login).
Features:
- User list with search and filters
- User details with usage statistics
- Create/edit/delete users
- Suspend/unsuspend accounts
- View login history
- Monitor active sessions
- Bulk operations
Rate Limiting
Default limits:
- Regular Users: 30/min, 500/hour, 5000/day
- Admin Users: 300/min, 5000/hour, 50000/day
Endpoint-specific limits are configured in user_rate_limiter.py
.
Troubleshooting
Common Issues
- "Token expired": Refresh token using
/api/auth/refresh
- "Account locked": Wait 30 minutes or contact admin
- "Rate limit exceeded": Check your usage limits
- "Invalid API key": Regenerate key in profile settings
Debug Mode
Enable debug logging:
import logging
logging.getLogger('auth').setLevel(logging.DEBUG)
Future Enhancements
- OAuth2 integration (Google, GitHub)
- Two-factor authentication
- Email verification workflow
- Password reset via email
- User groups and team management
- Fine-grained permissions
- API key scopes
- Usage quotas and billing