44 lines
1.2 KiB
Python
44 lines
1.2 KiB
Python
import uuid
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy import select, func
|
|
from pydantic import BaseModel
|
|
from ..dependencies import get_db
|
|
from ..models.user import User
|
|
from ..services.auth import hash_password, create_token
|
|
|
|
router = APIRouter(tags=["setup"])
|
|
|
|
|
|
class SetupRequest(BaseModel):
|
|
username: str
|
|
password: str
|
|
email: str = ""
|
|
|
|
|
|
@router.get("/api/setup/status")
|
|
async def setup_status(db: AsyncSession = Depends(get_db)):
|
|
result = await db.execute(select(func.count()).select_from(User))
|
|
count = result.scalar()
|
|
return {"needsSetup": count == 0}
|
|
|
|
|
|
@router.post("/api/setup")
|
|
async def run_setup(body: SetupRequest, db: AsyncSession = Depends(get_db)):
|
|
result = await db.execute(select(func.count()).select_from(User))
|
|
if result.scalar() > 0:
|
|
raise HTTPException(status_code=400, detail="Setup already completed")
|
|
|
|
admin = User(
|
|
id=str(uuid.uuid4()),
|
|
username=body.username,
|
|
email=body.email,
|
|
password_hash=hash_password(body.password),
|
|
is_admin=True,
|
|
)
|
|
db.add(admin)
|
|
await db.flush()
|
|
admin.token = create_token(admin.id)
|
|
await db.commit()
|
|
return {"success": True}
|