feat: add seed_admin.py for initial admin user creation
This commit is contained in:
@@ -0,0 +1,76 @@
|
|||||||
|
"""Seed script to create initial admin user.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
python scripts/seed_admin.py
|
||||||
|
|
||||||
|
Environment variables required:
|
||||||
|
DATABASE_URL=postgresql+asyncpg://user:pass@host:5432/dbname
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
# Add app to path
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
|
||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
from app.models.user import User
|
||||||
|
from app.services.auth_service import hash_password
|
||||||
|
from app.config import settings
|
||||||
|
|
||||||
|
|
||||||
|
async def seed_admin():
|
||||||
|
"""Create initial admin user if none exists."""
|
||||||
|
engine = create_async_engine(settings.DATABASE_URL, echo=False)
|
||||||
|
|
||||||
|
async with engine.begin() as conn:
|
||||||
|
# Create tables if they don't exist
|
||||||
|
from app.database import Base
|
||||||
|
await conn.run_sync(Base.metadata.create_all)
|
||||||
|
|
||||||
|
async with AsyncSession(engine) as session:
|
||||||
|
# Check if any admin exists
|
||||||
|
result = await session.execute(
|
||||||
|
text("SELECT COUNT(*) FROM users WHERE role = 'admin' AND is_active = true")
|
||||||
|
)
|
||||||
|
admin_count = result.scalar()
|
||||||
|
|
||||||
|
if admin_count > 0:
|
||||||
|
print("Admin user already exists. Skipping seed.")
|
||||||
|
return
|
||||||
|
|
||||||
|
# Create admin user
|
||||||
|
admin = User(
|
||||||
|
id=uuid.uuid4(),
|
||||||
|
email="admin@erp.local",
|
||||||
|
password_hash=hash_password("Admin123!ERP"),
|
||||||
|
full_name="System Administrator",
|
||||||
|
role="admin",
|
||||||
|
language="de",
|
||||||
|
is_active=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
session.add(admin)
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
|
print("=" * 50)
|
||||||
|
print("Admin user created successfully!")
|
||||||
|
print("=" * 50)
|
||||||
|
print(f"Email: admin@erp.local")
|
||||||
|
print(f"Password: Admin123!ERP")
|
||||||
|
print(f"Role: admin")
|
||||||
|
print(f"Language: de")
|
||||||
|
print("=" * 50)
|
||||||
|
print("⚠️ Please change the password after first login!")
|
||||||
|
print("=" * 50)
|
||||||
|
|
||||||
|
await engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(seed_admin())
|
||||||
Reference in New Issue
Block a user