33 lines
1020 B
Python
33 lines
1020 B
Python
from sqlalchemy.orm import Session
|
|
|
|
from app.auth import get_password_hash, get_user_by_email, get_user_by_username
|
|
from app.config import settings
|
|
from app.models.user import User, UserRole
|
|
|
|
|
|
def seed_admin_user(db: Session) -> None:
|
|
"""Create initial admin from .env if no user with that username exists."""
|
|
if not settings.admin_username or not settings.admin_password:
|
|
return
|
|
|
|
existing = get_user_by_username(db, settings.admin_username)
|
|
if existing:
|
|
if existing.role != UserRole.admin:
|
|
existing.role = UserRole.admin
|
|
db.commit()
|
|
return
|
|
|
|
email = settings.admin_email or f"{settings.admin_username}@localhost"
|
|
if get_user_by_email(db, email):
|
|
email = f"{settings.admin_username}.admin@localhost"
|
|
|
|
user = User(
|
|
email=email,
|
|
username=settings.admin_username,
|
|
hashed_password=get_password_hash(settings.admin_password),
|
|
role=UserRole.admin,
|
|
is_active=True,
|
|
)
|
|
db.add(user)
|
|
db.commit()
|