Spaces:
Sleeping
Sleeping
| """ | |
| Security utilities for authentication and authorization. | |
| """ | |
| from datetime import datetime, timedelta | |
| from typing import Optional | |
| from passlib.context import CryptContext | |
| import jwt | |
| from src.core.config import settings | |
| # Password hashing context - use argon2 for Python 3.13 compatibility | |
| pwd_context = CryptContext(schemes=["argon2"], deprecated="auto") | |
| def verify_password(plain_password: str, hashed_password: str) -> bool: | |
| """ | |
| Verify a plain password against a hashed password. | |
| Args: | |
| plain_password: Plain text password | |
| hashed_password: Hashed password to verify against | |
| Returns: | |
| bool: True if password matches, False otherwise | |
| """ | |
| return pwd_context.verify(plain_password, hashed_password) | |
| def get_password_hash(password: str) -> str: | |
| """ | |
| Hash a password using argon2. | |
| Args: | |
| password: Plain text password to hash | |
| Returns: | |
| str: Hashed password | |
| """ | |
| return pwd_context.hash(password) | |
| password = password[:72] | |
| return pwd_context.hash(password) | |
| def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str: | |
| """ | |
| Create a JWT access token. | |
| Args: | |
| data: Dictionary containing token payload | |
| expires_delta: Optional custom expiration time | |
| Returns: | |
| str: Encoded JWT token | |
| """ | |
| to_encode = data.copy() | |
| if expires_delta: | |
| expire = datetime.utcnow() + expires_delta | |
| else: | |
| expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) | |
| to_encode.update({"exp": expire}) | |
| encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) | |
| return encoded_jwt | |
| def decode_access_token(token: str) -> Optional[dict]: | |
| """ | |
| Decode and verify a JWT access token. | |
| Args: | |
| token: JWT token string to decode | |
| Returns: | |
| Optional[dict]: Decoded token payload or None if invalid | |
| """ | |
| try: | |
| payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]) | |
| return payload | |
| except jwt.PyJWTError: | |
| return None | |