From a88ebd40a71202767a57846b6be2c2c6b8172440 Mon Sep 17 00:00:00 2001 From: Felipe Cardoso Date: Tue, 4 Mar 2025 18:54:00 +0100 Subject: [PATCH] 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. --- .env.template | 2 +- backend/app/core/auth.py | 4 +++- backend/app/init_db.py | 52 ++++++++++++++++++++++++++++++++++++++++ backend/entrypoint.sh | 3 +++ 4 files changed, 59 insertions(+), 2 deletions(-) create mode 100644 backend/app/init_db.py diff --git a/.env.template b/.env.template index 91bc5d2..ebd0e2a 100644 --- a/.env.template +++ b/.env.template @@ -17,7 +17,7 @@ ENVIRONMENT=development DEBUG=true BACKEND_CORS_ORIGINS=["http://localhost:3000"] FIRST_SUPERUSER_EMAIL=admin@example.com -FIRST_SUPERUSER_PASSWORD=admin123 +FIRST_SUPERUSER_PASSWORD=Admin123 # Frontend settings FRONTEND_PORT=3000 diff --git a/backend/app/core/auth.py b/backend/app/core/auth.py index d2f6ca1..21ddaf1 100644 --- a/backend/app/core/auth.py +++ b/backend/app/core/auth.py @@ -1,4 +1,6 @@ -# app/core/auth.py +import logging +logging.getLogger('passlib').setLevel(logging.ERROR) + from datetime import datetime, timedelta, timezone from typing import Any, Dict, Optional, Union import uuid diff --git a/backend/app/init_db.py b/backend/app/init_db.py new file mode 100644 index 0000000..6f23267 --- /dev/null +++ b/backend/app/init_db.py @@ -0,0 +1,52 @@ +# 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() diff --git a/backend/entrypoint.sh b/backend/entrypoint.sh index fbf5b1d..bf060fd 100644 --- a/backend/entrypoint.sh +++ b/backend/entrypoint.sh @@ -4,5 +4,8 @@ echo "Starting Backend" # Apply database migrations alembic upgrade head + +python app/init_db.py + # Execute the command passed to docker run exec "$@" \ No newline at end of file