/
kuklindal
/
RealEstateAnalyzer
Обзор
Документация
Войти
/
kuklindal
/
RealEstateAnalyzer
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
develop
backend/auth.py
72 строки
2 KB
Daniil Kuklin
fixes
20 май 2026, 13:17
20 май 2026, 13:17
51eb5cc
Код
Авторство
О чём код?
from datetime import datetime, timedelta, timezone from fastapi import Depends, HTTPException, status from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from jose import JWTError, jwt from pwdlib import PasswordHash from sqlalchemy.orm import Session from backend.database import get_db from backend.models import User SECRET_KEY = "super_secret_key_change_me_123456" ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 password_hash = PasswordHash.recommended() security = HTTPBearer() def hash_password(password: str) -> str: return password_hash.hash(password) def verify_password(plain_password: str, hashed_password: str) -> bool: return password_hash.verify(plain_password, hashed_password) def create_access_token(data: dict) -> str: to_encode = data.copy() expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) to_encode.update({"exp": expire}) return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) def get_user_by_email(db: Session, email: str): return db.query(User).filter(User.email == email).first() def authenticate_user(db: Session, email: str, password: str): user = get_user_by_email(db, email) if not user: return None if not verify_password(password, user.hashed_password): return None return user def get_current_user( credentials: HTTPAuthorizationCredentials = Depends(security), db: Session = Depends(get_db), ): token = credentials.credentials credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) user_id = payload.get("sub") if user_id is None: raise credentials_exception except JWTError: raise credentials_exception user = db.query(User).filter(User.id == int(user_id)).first() if user is None: raise credentials_exception return user