auth.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. from datetime import datetime, timedelta
  2. from jose import JWTError, jwt
  3. from passlib.context import CryptContext
  4. from fastapi import HTTPException, Depends
  5. from fastapi.security import HTTPBearer
  6. SECRET_KEY = "your-secret-key-here-change-in-production"
  7. ALGORITHM = "HS256"
  8. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  9. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  10. security = HTTPBearer()
  11. def verify_password(plain_password, hashed_password):
  12. return pwd_context.verify(plain_password, hashed_password)
  13. def get_password_hash(password):
  14. return pwd_context.hash(password)
  15. def create_access_token(data: dict):
  16. to_encode = data.copy()
  17. expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  18. to_encode.update({"exp": expire})
  19. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  20. return encoded_jwt
  21. def verify_token(token: str):
  22. try:
  23. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  24. return payload
  25. except JWTError:
  26. return None
  27. # Добавьте эту функцию для зависимости
  28. async def get_current_user(token: str = Depends(security)):
  29. credentials_exception = HTTPException(
  30. status_code=401,
  31. detail="Could not validate credentials",
  32. headers={"WWW-Authenticate": "Bearer"},
  33. )
  34. payload = verify_token(token.credentials)
  35. if payload is None:
  36. raise credentials_exception
  37. username: str = payload.get("sub")
  38. if username is None:
  39. raise credentials_exception
  40. return {"sub": username}