mirror of
https://git.victorphan.net/basketballcantho/ten-project.git
synced 2026-08-05 21:43:10 +07:00
84 lines
2.9 KiB
Python
84 lines
2.9 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from ..database import get_db
|
|
from ..dependencies import require_admin
|
|
from ..models import User, UserStatus
|
|
from ..schemas import UserApprove, UserRoleUpdate, UserOut
|
|
|
|
router = APIRouter(prefix="/admin", tags=["admin"])
|
|
|
|
|
|
# ── GET /api/admin/users ──────────────────────────────────────────────────────
|
|
|
|
@router.get("/users", response_model=list[UserOut])
|
|
def list_users(
|
|
admin: User = Depends(require_admin),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""Return all users (any role / status). Admin only."""
|
|
return db.query(User).order_by(User.created_at.desc()).all()
|
|
|
|
|
|
# ── PATCH /api/admin/users/{user_id}/status ───────────────────────────────────
|
|
|
|
@router.patch("/users/{user_id}/status", response_model=UserOut)
|
|
def update_user_status(
|
|
user_id: int,
|
|
body: UserApprove,
|
|
admin: User = Depends(require_admin),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""Approve or reject a user account. Admin only."""
|
|
user = db.get(User, user_id)
|
|
if not user:
|
|
raise HTTPException(status_code=404, detail="User not found.")
|
|
if user.id == admin.id:
|
|
raise HTTPException(status_code=400, detail="Cannot change your own status.")
|
|
|
|
user.status = body.status
|
|
db.commit()
|
|
db.refresh(user)
|
|
return user
|
|
|
|
|
|
# ── PATCH /api/admin/users/{user_id}/role ─────────────────────────────────────
|
|
|
|
@router.patch("/users/{user_id}/role", response_model=UserOut)
|
|
def update_user_role(
|
|
user_id: int,
|
|
body: UserRoleUpdate,
|
|
admin: User = Depends(require_admin),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""Change a user's role. Admin only."""
|
|
user = db.get(User, user_id)
|
|
if not user:
|
|
raise HTTPException(status_code=404, detail="User not found.")
|
|
if user.id == admin.id:
|
|
raise HTTPException(status_code=400, detail="Cannot change your own role.")
|
|
|
|
user.role = body.role
|
|
db.commit()
|
|
db.refresh(user)
|
|
return user
|
|
|
|
|
|
# ── DELETE /api/admin/users/{user_id} ─────────────────────────────────────────
|
|
|
|
@router.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
def delete_user(
|
|
user_id: int,
|
|
admin: User = Depends(require_admin),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""Permanently delete a user and all their data. Admin only."""
|
|
user = db.get(User, user_id)
|
|
if not user:
|
|
raise HTTPException(status_code=404, detail="User not found.")
|
|
if user.id == admin.id:
|
|
raise HTTPException(status_code=400, detail="Cannot delete your own account.")
|
|
|
|
db.delete(user)
|
|
db.commit()
|