Spaces:
Running
Running
| import os | |
| from datetime import datetime, timedelta, timezone | |
| from typing import Optional, Dict, Any | |
| from jose import jwt, JWTError | |
| from passlib.context import CryptContext | |
| from fastapi import HTTPException, status, Depends | |
| from fastapi.security import OAuth2PasswordBearer | |
| # ========================================================= | |
| # ENV CONFIG | |
| # ========================================================= | |
| SECRET_KEY = os.getenv("SECRET_KEY") | |
| if not SECRET_KEY: | |
| raise RuntimeError("SECRET_KEY environment variable missing") | |
| ALGORITHM = os.getenv("ALGORITHM", "HS256") | |
| ACCESS_TOKEN_EXPIRE_MINUTES = int( | |
| os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "1440") | |
| ) | |
| # ========================================================= | |
| # PASSWORD HASHING | |
| # ========================================================= | |
| # IMPORTANT: | |
| # pbkdf2_sha256 avoids: | |
| # - bcrypt crashes | |
| # - bcrypt native dependency issues | |
| # - 72-byte limits | |
| # - passlib backend bugs | |
| # ========================================================= | |
| pwd_context = CryptContext( | |
| schemes=["pbkdf2_sha256"], | |
| deprecated="auto", | |
| ) | |
| def hash_password(password: str) -> str: | |
| if not password: | |
| raise ValueError("Password required") | |
| if len(password) < 8: | |
| raise ValueError("Password too short") | |
| return pwd_context.hash(password) | |
| def verify_password( | |
| plain_password: str, | |
| hashed_password: str, | |
| ) -> bool: | |
| try: | |
| return pwd_context.verify( | |
| plain_password, | |
| hashed_password, | |
| ) | |
| except Exception: | |
| return False | |
| # ========================================================= | |
| # JWT | |
| # ========================================================= | |
| def create_access_token( | |
| data: Dict[str, Any], | |
| expires_delta: Optional[timedelta] = None, | |
| ) -> str: | |
| to_encode = data.copy() | |
| expire = datetime.now(timezone.utc) + ( | |
| expires_delta | |
| if expires_delta | |
| else timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) | |
| ) | |
| to_encode.update({"exp": expire}) | |
| return jwt.encode( | |
| to_encode, | |
| SECRET_KEY, | |
| algorithm=ALGORITHM, | |
| ) | |
| def decode_token(token: str): | |
| try: | |
| return jwt.decode( | |
| token, | |
| SECRET_KEY, | |
| algorithms=[ALGORITHM], | |
| ) | |
| except JWTError: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid token", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| # ========================================================= | |
| # AUTH DEPENDENCY | |
| # ========================================================= | |
| oauth2_scheme = OAuth2PasswordBearer( | |
| tokenUrl="/api/auth/login" | |
| ) | |
| def get_current_user( | |
| token: str = Depends(oauth2_scheme) | |
| ): | |
| payload = decode_token(token) | |
| user_id = payload.get("sub") | |
| if not user_id: | |
| raise HTTPException( | |
| status_code=401, | |
| detail="Invalid authentication", | |
| ) | |
| return payload |