hp-studios-ai-content-agent/backend/app/api/users.py
DJP 3941af7b0b Admin: add user deletion
Backend:
  DELETE /users/:id (admin only, not self, blocked if last admin).
  Briefs are preserved (ON DELETE SET NULL on created_by).

Frontend:
  useDeleteUser hook + Actions column in UsersAdminPage with trash
  button. Own-account row shows '(you)' and the delete is disabled
  with a tooltip. Error detail surfaces in the toast on 400s (eg.
  'Cannot delete the only remaining admin').
2026-04-22 17:29:19 -04:00

102 lines
3.2 KiB
Python

from __future__ import annotations
from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, EmailStr
from sqlalchemy.orm import Session
import uuid
from app.core.deps import get_current_user, require_admin
from app.core.security import hash_password
from app.db.models import User
from app.db.session import get_db
router = APIRouter(prefix="/users", tags=["users"])
# ---------------------------------------------------------------------------
# Schemas
# ---------------------------------------------------------------------------
class CreateUserRequest(BaseModel):
email: EmailStr
name: str
password: str
role: str = "user"
class UserOut(BaseModel):
id: str
email: str
name: str
role: str
model_config = {"from_attributes": True}
# ---------------------------------------------------------------------------
# Routes
# ---------------------------------------------------------------------------
@router.post("", response_model=UserOut, status_code=status.HTTP_201_CREATED)
def create_user(
body: CreateUserRequest,
db: Session = Depends(get_db),
_admin: User = Depends(require_admin),
) -> Any:
if body.role not in ("admin", "user"):
raise HTTPException(status_code=400, detail="role must be 'admin' or 'user'")
existing = db.query(User).filter(User.email == body.email).first()
if existing:
raise HTTPException(status_code=409, detail="Email already registered")
user = User(
email=body.email,
name=body.name,
password_hash=hash_password(body.password),
role=body.role,
)
db.add(user)
db.commit()
return UserOut(id=str(user.id), email=user.email, name=user.name, role=user.role)
@router.get("", response_model=List[UserOut])
def list_users(
db: Session = Depends(get_db),
_admin: User = Depends(require_admin),
) -> Any:
users = db.query(User).order_by(User.created_at).all()
return [UserOut(id=str(u.id), email=u.email, name=u.name, role=u.role) for u in users]
@router.delete("/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_user(
user_id: str,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user),
) -> None:
if current_user.role != "admin":
raise HTTPException(status_code=403, detail="Admin only")
try:
uid = uuid.UUID(user_id)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid user id")
target = db.query(User).filter(User.id == uid).first()
if target is None:
raise HTTPException(status_code=404, detail="User not found")
if str(target.id) == str(current_user.id):
raise HTTPException(status_code=400, detail="You can't delete your own account")
# Don't let admins accidentally delete the last remaining admin.
if target.role == "admin":
admin_count = db.query(User).filter(User.role == "admin").count()
if admin_count <= 1:
raise HTTPException(status_code=400, detail="Cannot delete the only remaining admin")
# Briefs.created_by is ON DELETE SET NULL, so the user's briefs survive
# as orphaned rows (still visible to admins). No cascade wipe.
db.delete(target)
db.commit()