/
Pepegator
/
task-api
Обзор
Документация
Войти
/
Pepegator
/
task-api
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
feature/lab2
pythonProject2/security.py
54 строки
2 KB
Pol136
create docs
30 дек 2025, 11:01
30 дек 2025, 11:01
d230838
Код
Авторство
О чём код?
from passlib.context import CryptContext from datetime import datetime, timedelta from typing import Optional from fastapi import Depends, HTTPException, Header from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from sqlalchemy.orm import Session import jwt from config import settings from database import get_db, User pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") def hash_password(password: str) -> str: return pwd_context.hash(password) def verify_password(plain_password: str, hashed_password: str) -> bool: return pwd_context.verify(plain_password, hashed_password) def create_access_token(user_id: int, expires_delta: Optional[timedelta] = None) -> str: if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta(minutes=settings.access_token_expire_minutes) to_encode = {"sub": str(user_id), "exp": expire} encoded_jwt = jwt.encode(to_encode, settings.secret_key, algorithm=settings.algorithm) return encoded_jwt def decode_access_token(token: str) -> Optional[int]: try: payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm]) user_id: int = int(payload.get("sub")) return user_id except: return None security = HTTPBearer() async def get_current_user( credentials: HTTPAuthorizationCredentials = Depends(security), db: Session = Depends(get_db) ) -> User: token = credentials.credentials user_id = decode_access_token(token) if user_id is None: raise HTTPException(status_code=401, detail="Invalid token") user = db.query(User).filter(User.id == user_id).first() if user is None: raise HTTPException(status_code=401, detail="User not found") return user