 eda5b2d6d3
			
		
	
	eda5b2d6d3
	
	
	
		
			
			Major changes: - Consolidate 3 different User models into single unified model (models/user.py) - Use UUID primary keys throughout (matches existing database schema) - Add comprehensive authentication fields while preserving existing data - Remove duplicate User model from auth.py, keep APIKey/RefreshToken/TokenBlacklist - Update all imports to use unified User model consistently - Create database migration (002_add_auth_fields.sql) for safe schema upgrade - Fix frontend User interface to handle UUID string IDs - Add backward compatibility fields (name property, role field) - Maintain relationships for authentication features (api_keys, refresh_tokens) Schema conflicts resolved: ✅ Migration schema (UUID, 7 fields) + Basic model (Integer, 6 fields) + Auth model (Integer, 10 fields) → Unified model (UUID, 12 fields with full backward compatibility) ✅ Field inconsistencies (name vs full_name) resolved with compatibility property ✅ Database foreign key constraints updated for UUID relationships ✅ JWT token handling fixed for UUID user IDs This completes the holistic database schema unification requested after quick patching caused conflicts. All existing data preserved, full auth system functional. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
		
			
				
	
	
		
			126 lines
		
	
	
		
			3.8 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
			
		
		
	
	
			126 lines
		
	
	
		
			3.8 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
| """
 | |
| Database initialization script for Hive platform.
 | |
| Creates all tables and sets up initial data.
 | |
| """
 | |
| 
 | |
| import logging
 | |
| from sqlalchemy.orm import Session
 | |
| from app.core.database import engine, SessionLocal, Base
 | |
| from app.models.user import User
 | |
| from app.models.auth import API_SCOPES, APIKey
 | |
| 
 | |
| # Import all models to ensure they're registered with Base
 | |
| from app.models import user, auth, agent, project
 | |
| 
 | |
| def create_tables():
 | |
|     """Create all database tables."""
 | |
|     try:
 | |
|         # Create all tables using the unified Base
 | |
|         Base.metadata.create_all(bind=engine)
 | |
|         
 | |
|         # Add other model bases here
 | |
|         # WorkflowsBase.metadata.create_all(bind=engine)
 | |
|         # AgentsBase.metadata.create_all(bind=engine)
 | |
|         
 | |
|         logging.info("Database tables created successfully")
 | |
|         return True
 | |
|     except Exception as e:
 | |
|         logging.error(f"Failed to create database tables: {e}")
 | |
|         return False
 | |
| 
 | |
| 
 | |
| def create_initial_user(db: Session):
 | |
|     """Create initial admin user if none exists."""
 | |
|     try:
 | |
|         # Check if any users exist
 | |
|         user_count = db.query(User).count()
 | |
|         if user_count > 0:
 | |
|             logging.info("Users already exist, skipping initial user creation")
 | |
|             return True
 | |
|         
 | |
|         # Create initial admin user
 | |
|         admin_user = User(
 | |
|             username="admin",
 | |
|             email="admin@hive.local",
 | |
|             full_name="Hive Administrator",
 | |
|             hashed_password=User.hash_password("admin123"),  # Change this!
 | |
|             is_active=True,
 | |
|             is_superuser=True,
 | |
|             is_verified=True
 | |
|         )
 | |
|         
 | |
|         db.add(admin_user)
 | |
|         db.commit()
 | |
|         db.refresh(admin_user)
 | |
|         
 | |
|         logging.info("Initial admin user created: admin/admin123")
 | |
|         logging.warning("SECURITY: Please change the default admin password!")
 | |
|         
 | |
|         # Create initial API key for the admin user
 | |
|         from app.core.security import APIKeyManager
 | |
|         plain_key, hashed_key, prefix = APIKeyManager.generate_api_key()
 | |
|         
 | |
|         admin_api_key = APIKey(
 | |
|             user_id=admin_user.id,
 | |
|             name="Default Admin API Key",
 | |
|             key_hash=hashed_key,
 | |
|             key_prefix=prefix,
 | |
|             is_active=True
 | |
|         )
 | |
|         admin_api_key.set_scopes(["admin"])
 | |
|         
 | |
|         db.add(admin_api_key)
 | |
|         db.commit()
 | |
|         
 | |
|         logging.info(f"Initial admin API key created: {plain_key}")
 | |
|         logging.warning("SECURITY: Save this API key securely, it won't be shown again!")
 | |
|         
 | |
|         return True
 | |
|         
 | |
|     except Exception as e:
 | |
|         logging.error(f"Failed to create initial user: {e}")
 | |
|         db.rollback()
 | |
|         return False
 | |
| 
 | |
| 
 | |
| def initialize_database():
 | |
|     """Initialize the complete database."""
 | |
|     logging.info("Starting database initialization...")
 | |
|     
 | |
|     # Create tables
 | |
|     if not create_tables():
 | |
|         return False
 | |
|     
 | |
|     # Create initial data
 | |
|     db = SessionLocal()
 | |
|     try:
 | |
|         # Create initial admin user
 | |
|         if not create_initial_user(db):
 | |
|             return False
 | |
|         
 | |
|         logging.info("Database initialization completed successfully")
 | |
|         return True
 | |
|         
 | |
|     except Exception as e:
 | |
|         logging.error(f"Database initialization failed: {e}")
 | |
|         return False
 | |
|     finally:
 | |
|         db.close()
 | |
| 
 | |
| 
 | |
| if __name__ == "__main__":
 | |
|     # Configure logging
 | |
|     logging.basicConfig(
 | |
|         level=logging.INFO,
 | |
|         format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
 | |
|     )
 | |
|     
 | |
|     # Initialize database
 | |
|     success = initialize_database()
 | |
|     if success:
 | |
|         print("✅ Database initialization completed successfully")
 | |
|         print("🔑 Default admin credentials: admin/admin123")
 | |
|         print("⚠️  SECURITY: Please change the default password immediately!")
 | |
|     else:
 | |
|         print("❌ Database initialization failed")
 | |
|         exit(1) |