0803d86e38
First registered user becomes admin automatically. Admins see a "Manage Users" button in the dashboard header that opens a new /admin page for listing, creating, and deleting users. Backend enforces admin-only access on /admin/* routes. Startup migration adds the is_admin column to existing SQLite databases. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
58 lines
1.8 KiB
Python
58 lines
1.8 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
from pydantic import BaseModel
|
|
from typing import List
|
|
|
|
from ..database import get_db
|
|
from .. import models
|
|
from ..auth import hash_password
|
|
from ..dependencies import get_current_admin
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
class UserOut(BaseModel):
|
|
id: int
|
|
username: str
|
|
is_admin: bool
|
|
|
|
class Config:
|
|
from_attributes = True
|
|
|
|
|
|
class UserCreate(BaseModel):
|
|
username: str
|
|
password: str
|
|
is_admin: bool = False
|
|
|
|
|
|
@router.get("/users", response_model=List[UserOut])
|
|
def list_users(db: Session = Depends(get_db), _: models.User = Depends(get_current_admin)):
|
|
return db.query(models.User).all()
|
|
|
|
|
|
@router.post("/users", response_model=UserOut, status_code=status.HTTP_201_CREATED)
|
|
def create_user(user_in: UserCreate, db: Session = Depends(get_db), _: models.User = Depends(get_current_admin)):
|
|
if db.query(models.User).filter(models.User.username == user_in.username).first():
|
|
raise HTTPException(status_code=400, detail="Username already taken")
|
|
user = models.User(
|
|
username=user_in.username,
|
|
password=hash_password(user_in.password),
|
|
is_admin=user_in.is_admin,
|
|
)
|
|
db.add(user)
|
|
db.commit()
|
|
db.refresh(user)
|
|
return user
|
|
|
|
|
|
@router.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
def delete_user(user_id: int, db: Session = Depends(get_db), current_admin: models.User = Depends(get_current_admin)):
|
|
if user_id == current_admin.id:
|
|
raise HTTPException(status_code=400, detail="Cannot delete your own account")
|
|
user = db.query(models.User).filter(models.User.id == user_id).first()
|
|
if not user:
|
|
raise HTTPException(status_code=404, detail="User not found")
|
|
db.delete(user)
|
|
db.commit()
|