Files
eventspace/backend/app/init_db.py
Felipe Cardoso a88ebd40a7
All checks were successful
Build and Push Docker Images / changes (push) Successful in 5s
Build and Push Docker Images / build-backend (push) Successful in 51s
Build and Push Docker Images / build-frontend (push) Has been skipped
Add database initialization for first superuser setup
Introduced a script to create the initial superuser during app startup if none exists. Updated the entrypoint to call this script and added stricter logging for passlib. Adjusted .env.template for a stronger default superuser password.
2025-03-04 18:54:00 +01:00

53 lines
1.6 KiB
Python

# app/core/init_db.py
import logging
from typing import Optional
from sqlalchemy.orm import Session
from app.core.config import settings
from app.crud.user import user as user_crud
from app.schemas.users import UserCreate
from app.core.database import engine
logger = logging.getLogger(__name__)
def init_db(db: Session) -> Optional[UserCreate]:
"""
Initialize database with first superuser if settings are configured and user doesn't exist.
"""
if not settings.FIRST_SUPERUSER_EMAIL or not settings.FIRST_SUPERUSER_PASSWORD:
logger.warning("First superuser credentials not configured in settings")
return None
try:
# Check if superuser already exists
existing_user = user_crud.get_by_email(
db, email=settings.FIRST_SUPERUSER_EMAIL
)
if existing_user:
logger.info("Superuser already exists, skipping creation")
return None
# Create superuser if doesn't exist
user_in = UserCreate(
email=settings.FIRST_SUPERUSER_EMAIL,
password=settings.FIRST_SUPERUSER_PASSWORD,
first_name="Admin", # Required by your schema
last_name="User", # Required by your schema
is_superuser=True
)
user = user_crud.create(db, obj_in=user_in)
logger.info(f"Created first superuser: {user.email}")
return user
except Exception as e:
logger.error(f"Error creating superuser: {e}")
raise
if __name__ == "__main__":
with Session(engine) as session:
try:
init_db(session)
finally:
session.close()