first commit
This commit is contained in:
45
scripts/init_db.py
Normal file
45
scripts/init_db.py
Normal file
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create initial admin user"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
import os
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
import bcrypt
|
||||
|
||||
|
||||
ADMIN_PASSWORD_HASH = bcrypt.hashpw("admin123".encode(), bcrypt.gensalt()).decode()
|
||||
|
||||
|
||||
async def create_admin():
|
||||
DATABASE_URL = os.environ.get(
|
||||
"DATABASE_URL", "postgresql+asyncpg://postgres:postgres@localhost:5432/planet_db"
|
||||
)
|
||||
engine = create_async_engine(DATABASE_URL, echo=False)
|
||||
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
||||
|
||||
async with async_session() as session:
|
||||
result = await session.execute(text("SELECT id FROM users WHERE username = 'admin'"))
|
||||
if result.fetchone():
|
||||
print("Admin user already exists")
|
||||
return
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
INSERT INTO users (username, email, password_hash, role, is_active, created_at, updated_at)
|
||||
VALUES ('admin', 'admin@planet.local', :password, 'super_admin', true, NOW(), NOW())
|
||||
"""),
|
||||
{"password": ADMIN_PASSWORD_HASH},
|
||||
)
|
||||
await session.commit()
|
||||
print(f"Admin user created: admin / admin123")
|
||||
print(f"Hash: {ADMIN_PASSWORD_HASH}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(create_admin())
|
||||
Reference in New Issue
Block a user