Spaces:
Runtime error
Runtime error
| import hashlib | |
| import os | |
| from datetime import datetime, timedelta | |
| from typing import Optional | |
| from fastapi import Depends, HTTPException, status | |
| from fastapi.security import OAuth2PasswordBearer | |
| from jose import JWTError, jwt | |
| from sqlmodel import Session, select | |
| from app.database import get_session | |
| from app.models import User | |
| # Configuration | |
| SECRET_KEY = "super-secret-key-change-this-in-production" | |
| ALGORITHM = "HS256" | |
| ACCESS_TOKEN_EXPIRE_MINUTES = 30 | |
| oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/token") | |
| def get_password_hash(password: str) -> str: | |
| """Hash a password using SHA-256 with a random salt.""" | |
| salt = os.urandom(32) | |
| key = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000) | |
| return salt.hex() + ':' + key.hex() | |
| def verify_password(plain_password: str, hashed_password: str) -> bool: | |
| """Verify a password against its stored hash.""" | |
| try: | |
| salt_hex, key_hex = hashed_password.split(':', 1) | |
| salt = bytes.fromhex(salt_hex) | |
| key = bytes.fromhex(key_hex) | |
| new_key = hashlib.pbkdf2_hmac('sha256', plain_password.encode('utf-8'), salt, 100000) | |
| return new_key == key | |
| except (ValueError, AttributeError): | |
| return False | |
| def create_access_token(data: dict, expires_delta: Optional[timedelta] = None): | |
| to_encode = data.copy() | |
| if expires_delta: | |
| expire = datetime.utcnow() + expires_delta | |
| else: | |
| expire = datetime.utcnow() + timedelta(minutes=15) | |
| to_encode.update({"exp": expire}) | |
| encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) | |
| return encoded_jwt | |
| async def get_current_user(token: str = Depends(oauth2_scheme), session: Session = Depends(get_session)): | |
| credentials_exception = HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Could not validate credentials", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| try: | |
| payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) | |
| username: str = payload.get("sub") | |
| if username is None: | |
| raise credentials_exception | |
| except JWTError: | |
| raise credentials_exception | |
| user = session.exec(select(User).where(User.username == username)).first() | |
| if user is None: | |
| raise credentials_exception | |
| return user | |