talk2me/migrations.py
Adolfo Delorenzo fa951c3141 Add comprehensive database integration, authentication, and admin dashboard
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>
2025-06-03 18:21:56 -06:00

135 lines
3.6 KiB
Python

# Database migration scripts
import os
import sys
import logging
from flask import Flask
from flask_migrate import Migrate, init, migrate, upgrade
from database import db, init_db
from config import Config
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def create_app():
"""Create Flask app for migrations"""
app = Flask(__name__)
# Load configuration
config = Config()
app.config.from_object(config)
# Initialize database
init_db(app)
return app
def init_migrations():
"""Initialize migration repository"""
app = create_app()
with app.app_context():
# Initialize Flask-Migrate
migrate_instance = Migrate(app, db)
# Initialize migration repository
try:
init()
logger.info("Migration repository initialized")
except Exception as e:
logger.error(f"Failed to initialize migrations: {e}")
return False
return True
def create_migration(message="Auto migration"):
"""Create a new migration"""
app = create_app()
with app.app_context():
# Initialize Flask-Migrate
migrate_instance = Migrate(app, db)
try:
migrate(message=message)
logger.info(f"Migration created: {message}")
except Exception as e:
logger.error(f"Failed to create migration: {e}")
return False
return True
def run_migrations():
"""Run pending migrations"""
app = create_app()
with app.app_context():
# Initialize Flask-Migrate
migrate_instance = Migrate(app, db)
try:
upgrade()
logger.info("Migrations completed successfully")
except Exception as e:
logger.error(f"Failed to run migrations: {e}")
return False
return True
def create_initial_data():
"""Create initial data if needed"""
app = create_app()
with app.app_context():
try:
# Add any initial data here
# For example, creating default API keys, admin users, etc.
db.session.commit()
logger.info("Initial data created")
except Exception as e:
db.session.rollback()
logger.error(f"Failed to create initial data: {e}")
return False
return True
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python migrations.py [init|create|run|seed]")
sys.exit(1)
command = sys.argv[1]
if command == "init":
if init_migrations():
print("Migration repository initialized successfully")
else:
print("Failed to initialize migrations")
sys.exit(1)
elif command == "create":
message = sys.argv[2] if len(sys.argv) > 2 else "Auto migration"
if create_migration(message):
print(f"Migration created: {message}")
else:
print("Failed to create migration")
sys.exit(1)
elif command == "run":
if run_migrations():
print("Migrations completed successfully")
else:
print("Failed to run migrations")
sys.exit(1)
elif command == "seed":
if create_initial_data():
print("Initial data created successfully")
else:
print("Failed to create initial data")
sys.exit(1)
else:
print(f"Unknown command: {command}")
print("Available commands: init, create, run, seed")
sys.exit(1)