Обновление приложения
This commit is contained in:
0
backend/app/auth/__init__.py
Normal file
0
backend/app/auth/__init__.py
Normal file
54
backend/app/auth/dependencies.py
Normal file
54
backend/app/auth/dependencies.py
Normal file
@@ -0,0 +1,54 @@
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from jose import JWTError
|
||||
from sqlalchemy.orm import Session
|
||||
from app.auth.security import decode_token
|
||||
from app.database import get_db
|
||||
from app.models.user import User
|
||||
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")
|
||||
|
||||
ROLES = {"admin": 4, "accountant": 3, "user": 2, "viewer": 1}
|
||||
|
||||
|
||||
def _get_current_user(token: str, db: Session) -> User:
|
||||
credentials_exc = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
try:
|
||||
payload = decode_token(token)
|
||||
if payload.get("type") != "access":
|
||||
raise credentials_exc
|
||||
user_id = int(payload["sub"])
|
||||
except (JWTError, KeyError, ValueError):
|
||||
raise credentials_exc
|
||||
|
||||
user = db.get(User, user_id)
|
||||
if not user or not user.is_active:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User inactive or not found")
|
||||
return user
|
||||
|
||||
|
||||
def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)) -> User:
|
||||
return _get_current_user(token, db)
|
||||
|
||||
|
||||
def require_role(minimum_role: str):
|
||||
"""Dependency factory — blocks users whose role rank is below minimum_role."""
|
||||
min_rank = ROLES[minimum_role]
|
||||
|
||||
def _check(current_user: User = Depends(get_current_user)) -> User:
|
||||
user_rank = ROLES.get(current_user.role.name, 0)
|
||||
if user_rank < min_rank:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Insufficient permissions")
|
||||
return current_user
|
||||
|
||||
return _check
|
||||
|
||||
|
||||
require_viewer = Depends(require_role("viewer"))
|
||||
require_user = Depends(require_role("user"))
|
||||
require_accountant = Depends(require_role("accountant"))
|
||||
require_admin = Depends(require_role("admin"))
|
||||
41
backend/app/auth/security.py
Normal file
41
backend/app/auth/security.py
Normal file
@@ -0,0 +1,41 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
from app.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return pwd_context.hash(password)
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
return pwd_context.verify(plain, hashed)
|
||||
|
||||
|
||||
def _create_token(data: dict[str, Any], expires_delta: timedelta) -> str:
|
||||
payload = data.copy()
|
||||
payload["exp"] = datetime.now(timezone.utc) + expires_delta
|
||||
return jwt.encode(payload, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
|
||||
|
||||
def create_access_token(user_id: int, role: str) -> str:
|
||||
return _create_token(
|
||||
{"sub": str(user_id), "role": role, "type": "access"},
|
||||
timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES),
|
||||
)
|
||||
|
||||
|
||||
def create_refresh_token(user_id: int) -> str:
|
||||
return _create_token(
|
||||
{"sub": str(user_id), "type": "refresh"},
|
||||
timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS),
|
||||
)
|
||||
|
||||
|
||||
def decode_token(token: str) -> dict[str, Any]:
|
||||
return jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
||||
Reference in New Issue
Block a user