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.
53 lines
1.6 KiB
Python
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()
|