From b2f8656db6e34fed3936e53ba438cb4b34ade21d Mon Sep 17 00:00:00 2001 From: Agzamus Date: Mon, 12 Oct 2026 16:29:23 +0300 Subject: [PATCH] =?UTF-8?q?feat:=206.2=20=D0=A1=D0=BE=D0=B7=D0=B4=D0=B0?= =?UTF-8?q?=D1=82=D1=8C=20=D0=BC=D0=BE=D0=B4=D1=83=D0=BB=D1=8C=20`app/core?= =?UTF-8?q?/deps.py`:?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/core/deps.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 app/core/deps.py diff --git a/app/core/deps.py b/app/core/deps.py new file mode 100644 index 0000000..0dd343c --- /dev/null +++ b/app/core/deps.py @@ -0,0 +1,43 @@ +from fastapi import Depends, Header, HTTPException, status +from sqlalchemy.orm import Session + +from app.core.jwt import decode_token +from app.db import get_db +from app.models import User + + +# Читает заголовок Authorization: Bearer , +# декодирует, ищет пользователя по sub, проверяет is_active; +# при ошибке бросает HTTPException(401); +def get_current_user( + authorization: str | None = Header(default=None), + db: Session = Depends(get_db), +) -> User: + if not authorization or not authorization.lower().startswith("bearer "): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, detail="Authentication required" + ) + token = authorization.split(" ", 1)[1] + try: + payload = decode_token(token) + except ValueError as exc: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token" + ) from exc + + sub = payload.get("sub") + user = db.get(User, int(sub)) if isinstance(sub, str) and sub.isdigit() else None + if user is None or not user.is_active: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token" + ) + return user + + +# обёртка над get_current_user, дополнительно проверяет is_admin, иначе HTTPException(403) +def require_admin(user: User = Depends(get_current_user)) -> User: + if not user.is_admin: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, detail="Admin privileges required" + ) + return user