77 lines
2.3 KiB
Python
77 lines
2.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Create initial admin user with pre-generated hash"""
|
|
|
|
import asyncio
|
|
import sys
|
|
|
|
sys.path.insert(0, "/app")
|
|
|
|
from sqlalchemy import text
|
|
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
|
from sqlalchemy.orm import sessionmaker
|
|
import bcrypt
|
|
|
|
|
|
DEFAULT_LOGIN_USERS = (
|
|
{
|
|
"username": "admin",
|
|
"email": "admin@planet.local",
|
|
"password": "admin123",
|
|
"role": "super_admin",
|
|
},
|
|
{
|
|
"username": "linkong",
|
|
"email": "linkong@planet.local",
|
|
"password": "12345678",
|
|
"role": "super_admin",
|
|
},
|
|
)
|
|
|
|
|
|
async def create_admin():
|
|
DATABASE_URL = "postgresql+asyncpg://postgres:postgres@postgres: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:
|
|
created = []
|
|
for default_user in DEFAULT_LOGIN_USERS:
|
|
result = await session.execute(
|
|
text("SELECT id FROM users WHERE username = :username"),
|
|
{"username": default_user["username"]},
|
|
)
|
|
if result.fetchone():
|
|
continue
|
|
|
|
password_hash = bcrypt.hashpw(
|
|
default_user["password"].encode(), bcrypt.gensalt()
|
|
).decode()
|
|
await session.execute(
|
|
text("""
|
|
INSERT INTO users (username, email, password_hash, role, is_active, created_at, updated_at)
|
|
VALUES (:username, :email, :password, :role, true, NOW(), NOW())
|
|
"""),
|
|
{
|
|
"username": default_user["username"],
|
|
"email": default_user["email"],
|
|
"password": password_hash,
|
|
"role": default_user["role"],
|
|
},
|
|
)
|
|
created.append((default_user, password_hash))
|
|
|
|
await session.commit()
|
|
if not created:
|
|
print("Default login users already exist")
|
|
return
|
|
|
|
for default_user, password_hash in created:
|
|
print(
|
|
f"Default login user created: {default_user['username']} / {default_user['password']}"
|
|
)
|
|
print(f"Hash: {password_hash}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(create_admin())
|