Spaces:
Running
Running
Download backend/app/core/security.py from axeronis/microfunnel-api: direct link, hf CLI and curl.
- Browser
- Download file 2.45 kB
-
https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/backend/app/core/security.py
- Command line
-
hf download hf://spaces/axeronis/microfunnel-api/backend/app/core/security.py
-
curl -L -o security.py https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/backend/app/core/security.py
2.45 kB
| """Security utilities for password hashing and JWT token management.""" | |
| from datetime import datetime, timedelta | |
| from typing import Optional | |
| import bcrypt | |
| import jwt | |
| from fastapi import HTTPException, status | |
| from app.core.config import settings | |
| # Password hashing context (Removed passlib due to bcrypt compatibility issues) | |
| def get_password_hash(password: str) -> str: | |
| """ | |
| Hash a password using bcrypt. | |
| """ | |
| pwd_bytes = password.encode('utf-8') | |
| salt = bcrypt.gensalt() | |
| return bcrypt.hashpw(pwd_bytes, salt).decode('utf-8') | |
| def verify_password(plain_password: str, hashed_password: str) -> bool: | |
| """ | |
| Verify a password against a hash. | |
| """ | |
| try: | |
| pwd_bytes = plain_password.encode('utf-8') | |
| hash_bytes = hashed_password.encode('utf-8') | |
| return bcrypt.checkpw(pwd_bytes, hash_bytes) | |
| except Exception: | |
| return False | |
| def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str: | |
| """ | |
| Create JWT access token. | |
| Args: | |
| data: Dictionary containing the claims to encode in the token | |
| expires_delta: Optional custom expiration time | |
| Returns: | |
| Encoded JWT token string | |
| """ | |
| 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) -> dict: | |
| """ | |
| Decode and verify JWT access token. | |
| Args: | |
| token: JWT token string | |
| Returns: | |
| Dictionary containing the decoded payload | |
| Raises: | |
| HTTPException: If token is expired or invalid | |
| """ | |
| try: | |
| payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]) | |
| return payload | |
| except jwt.ExpiredSignatureError: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Token has expired", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| except jwt.InvalidTokenError: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid token", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |