1
0
mirror of https://gitlab.com/MoonTestUse1/AdministrationItDepartmens.git synced 2025-08-14 00:25:46 +02:00

Fix tests

This commit is contained in:
MoonTestUse1
2025-01-06 23:40:39 +06:00
parent 161361609d
commit fec52c777b
17 changed files with 249 additions and 368 deletions

View File

@@ -7,7 +7,7 @@ import re
from .jwt import verify_token
from ..database import get_db
from ..models.employee import Employee
from ..crud import employees
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
security = HTTPBearer(auto_error=False)
@@ -23,7 +23,7 @@ def verify_password(plain_password: str, hashed_password: str) -> bool:
def get_current_admin(
credentials: HTTPAuthorizationCredentials = Depends(security),
db: Session = Depends(get_db)
) -> Employee:
) -> dict:
"""Get current admin from token"""
if not credentials:
raise HTTPException(
@@ -37,28 +37,27 @@ def get_current_admin(
payload = verify_token(token, db)
employee_id = int(payload.get("sub"))
# Получаем сотрудника из БД
from ..crud.employees import get_employee
employee = get_employee(db, employee_id)
# Проверяем, что это админ
employee = employees.get_employee(db, employee_id)
if not employee or not employee.is_admin:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
status_code=status.HTTP_403_FORBIDDEN,
detail="Not enough permissions",
headers={"WWW-Authenticate": "Bearer"},
)
return employee
except Exception:
except Exception as e:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
def get_current_employee(
credentials: HTTPAuthorizationCredentials = Depends(security),
db: Session = Depends(get_db)
) -> Employee:
) -> dict:
"""Get current employee from token"""
if not credentials:
raise HTTPException(
@@ -72,13 +71,12 @@ def get_current_employee(
payload = verify_token(token, db)
employee_id = int(payload.get("sub"))
# Получаем сотрудника из БД
from ..crud.employees import get_employee
employee = get_employee(db, employee_id)
# Проверяем существование сотрудника
employee = employees.get_employee(db, employee_id)
if not employee:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
detail="Employee not found",
headers={"WWW-Authenticate": "Bearer"},
)
@@ -86,6 +84,6 @@ def get_current_employee(
except Exception:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)

View File

@@ -1,22 +1,13 @@
"""JWT utilities"""
from datetime import datetime, timedelta
from typing import Optional
from jose import JWTError, jwt
from fastapi import HTTPException, status
from redis import Redis
from sqlalchemy.orm import Session
from ..core.config import settings
from ..models.token import Token
from ..crud.employees import get_employee
redis = Redis(
host=settings.REDIS_HOST,
port=settings.REDIS_PORT,
decode_responses=True
)
def create_access_token(data: dict) -> str:
"""Create access token"""
to_encode = data.copy()
expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
@@ -24,59 +15,26 @@ def create_access_token(data: dict) -> str:
return encoded_jwt
def verify_token(token: str, db: Session) -> dict:
"""Verify token"""
try:
# Проверяем, что токен действителен
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
user_id: int = payload.get("sub")
if user_id is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
)
# Проверяем токен в Redis
if not redis.get(f"token:{token}"):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
)
return payload
except JWTError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
)
return None
def create_and_save_token(user_id: int, db: Session) -> str:
# Создаем JWT токен
access_token = create_access_token({"sub": str(user_id)})
def create_and_save_token(employee_id: int, db: Session) -> str:
"""Create and save token"""
# Создаем токен
access_token = create_access_token({"sub": str(employee_id)})
# Сохраняем в БД
# Сохраняем токен в базу
db_token = Token(
token=access_token,
user_id=user_id
employee_id=employee_id
)
db.add(db_token)
db.commit()
db.refresh(db_token)
# Кэшируем в Redis
redis.setex(
f"token:{access_token}",
timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES),
"valid"
)
return access_token
def get_current_employee(token: str, db: Session):
payload = verify_token(token, db)
employee_id = int(payload.get("sub"))
if employee_id == -1: # Для админа
return {"is_admin": True}
employee = get_employee(db, employee_id)
if employee is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Employee not found",
)
return employee
return access_token