feat: admin-benutzerverwaltung und start-admin aus env
- GET/POST /api/admin/users, GET/PATCH/DELETE /api/admin/users/{id}
- Deaktivieren und Passwort-Reset beenden alle Sessions des Benutzers
- kein Ändern/Löschen des eigenen Accounts, letzter aktiver Admin geschützt
- INITIAL_ADMIN_USERNAME/PASSWORD legen den ersten Admin an, solange keine Benutzer existieren
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5b4545b60f
commit
e9585b395c
5 files changed
+307
-2
No files matched your search
@@ -0,0 +1,44 @@
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
|
||||
from app.api.deps import AdminUser, DbSession
|
||||
from app.models import User
|
||||
from app.schemas.auth import UserOut
|
||||
from app.schemas.users import UserCreate, UserUpdate
|
||||
from app.services import users as user_service
|
||||
|
||||
router = APIRouter(prefix="/admin", tags=["admin"])
|
||||
|
||||
|
||||
def _get_user_or_404(db: DbSession, user_id: int) -> User:
|
||||
user = db.get(User, user_id)
|
||||
if user is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Benutzer nicht gefunden.")
|
||||
return user
|
||||
|
||||
|
||||
@router.get("/users", response_model=list[UserOut])
|
||||
def list_users(_admin: AdminUser, db: DbSession):
|
||||
return user_service.list_users(db)
|
||||
|
||||
|
||||
@router.post("/users", response_model=UserOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_user(body: UserCreate, _admin: AdminUser, db: DbSession):
|
||||
return user_service.create_user(db, body.username, body.password, body.role)
|
||||
|
||||
|
||||
@router.get("/users/{user_id}", response_model=UserOut)
|
||||
def get_user(user_id: int, _admin: AdminUser, db: DbSession):
|
||||
return _get_user_or_404(db, user_id)
|
||||
|
||||
|
||||
@router.patch("/users/{user_id}", response_model=UserOut)
|
||||
def update_user(user_id: int, body: UserUpdate, admin: AdminUser, db: DbSession):
|
||||
target = _get_user_or_404(db, user_id)
|
||||
return user_service.update_user(
|
||||
db, admin, target, role=body.role, is_active=body.is_active, password=body.password
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_user(user_id: int, admin: AdminUser, db: DbSession) -> None:
|
||||
user_service.delete_user(db, admin, _get_user_or_404(db, user_id))
|
||||
+25
-2
@@ -9,13 +9,13 @@ from fastapi.concurrency import run_in_threadpool
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
|
||||
from app import __version__
|
||||
from app.api import auth, health
|
||||
from app.api import admin, auth, health
|
||||
from app.config import get_settings
|
||||
from app.db import _session_factory
|
||||
from app.middleware import OriginCheckMiddleware
|
||||
from app.services.auth import delete_old_login_attempts
|
||||
from app.services.sessions import delete_expired_sessions
|
||||
from app.services.users import UserError
|
||||
from app.services.users import UserError, bootstrap_initial_admin
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -39,8 +39,30 @@ async def _cleanup_loop() -> None:
|
||||
await asyncio.sleep(CLEANUP_INTERVAL_SECONDS)
|
||||
|
||||
|
||||
def _bootstrap_admin() -> None:
|
||||
settings = get_settings()
|
||||
if not (settings.initial_admin_username and settings.initial_admin_password):
|
||||
return
|
||||
with _session_factory()() as db:
|
||||
try:
|
||||
user = bootstrap_initial_admin(
|
||||
db, settings.initial_admin_username, settings.initial_admin_password
|
||||
)
|
||||
except UserError as exc:
|
||||
logger.error("INITIAL_ADMIN_* ignored: %s", exc)
|
||||
return
|
||||
if user is not None:
|
||||
logger.warning(
|
||||
"Initial admin '%s' created from INITIAL_ADMIN_*; remove these from .env now.",
|
||||
user.username,
|
||||
)
|
||||
else:
|
||||
logger.info("INITIAL_ADMIN_* ignored: users already exist; remove them from .env.")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
|
||||
await run_in_threadpool(_bootstrap_admin)
|
||||
task = asyncio.create_task(_cleanup_loop())
|
||||
try:
|
||||
yield
|
||||
@@ -76,6 +98,7 @@ def create_app() -> FastAPI:
|
||||
app.add_middleware(OriginCheckMiddleware, allowed_origins=settings.allowed_origin_list)
|
||||
app.include_router(health.router, prefix="/api")
|
||||
app.include_router(auth.router, prefix="/api")
|
||||
app.include_router(admin.router, prefix="/api")
|
||||
|
||||
@app.exception_handler(UserError)
|
||||
def user_error_handler(_request: Request, exc: UserError) -> JSONResponse:
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.models import Role
|
||||
|
||||
|
||||
class UserCreate(BaseModel):
|
||||
username: str = Field(min_length=1, max_length=64)
|
||||
password: str = Field(min_length=1, max_length=1024)
|
||||
role: Role = Role.USER
|
||||
|
||||
|
||||
class UserUpdate(BaseModel):
|
||||
role: Role | None = None
|
||||
is_active: bool | None = None
|
||||
password: str | None = Field(default=None, min_length=1, max_length=1024)
|
||||
@@ -68,3 +68,66 @@ def set_password(
|
||||
stmt = stmt.where(UserSession.id != keep_session_id)
|
||||
db.execute(stmt)
|
||||
db.commit()
|
||||
|
||||
|
||||
def list_users(db: Session) -> list[User]:
|
||||
return list(db.scalars(select(User).order_by(User.username)))
|
||||
|
||||
|
||||
def _ensure_other_active_admin(db: Session, target: User) -> None:
|
||||
others = db.scalar(
|
||||
select(func.count())
|
||||
.select_from(User)
|
||||
.where(User.role == Role.ADMIN, User.is_active.is_(True), User.id != target.id)
|
||||
)
|
||||
if not others:
|
||||
raise UserError("Es muss mindestens ein aktiver Administrator bestehen bleiben.")
|
||||
|
||||
|
||||
def update_user(
|
||||
db: Session,
|
||||
actor: User,
|
||||
target: User,
|
||||
*,
|
||||
role: Role | None = None,
|
||||
is_active: bool | None = None,
|
||||
password: str | None = None,
|
||||
) -> User:
|
||||
"""Admin change of another user; deactivation and password reset end all sessions."""
|
||||
if actor.id == target.id:
|
||||
raise UserError("Den eigenen Account bitte unter „Konto“ ändern.")
|
||||
|
||||
loses_admin = (
|
||||
target.is_admin
|
||||
and target.is_active
|
||||
and ((role is not None and role != Role.ADMIN) or is_active is False)
|
||||
)
|
||||
if loses_admin:
|
||||
_ensure_other_active_admin(db, target)
|
||||
|
||||
if role is not None:
|
||||
target.role = role
|
||||
if is_active is not None:
|
||||
target.is_active = is_active
|
||||
if password is not None:
|
||||
set_password(db, target, password) # commits and revokes sessions
|
||||
if is_active is False:
|
||||
db.execute(delete(UserSession).where(UserSession.user_id == target.id))
|
||||
db.commit()
|
||||
return target
|
||||
|
||||
|
||||
def delete_user(db: Session, actor: User, target: User) -> None:
|
||||
if actor.id == target.id:
|
||||
raise UserError("Der eigene Account kann nicht gelöscht werden.")
|
||||
if target.is_admin and target.is_active:
|
||||
_ensure_other_active_admin(db, target)
|
||||
db.delete(target)
|
||||
db.commit()
|
||||
|
||||
|
||||
def bootstrap_initial_admin(db: Session, username: str, password: str) -> User | None:
|
||||
"""Create the first admin from configuration; does nothing once any user exists."""
|
||||
if count_users(db) > 0:
|
||||
return None
|
||||
return create_user(db, username, password, Role.ADMIN)
|
||||
Reference in new issue
Block a user