CoolFace
Apppublic

bashartc14/todo_backend

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
auth.py63 linesDownload Raw Back to root
1 2from fastapi import Depends, HTTPException, Request, status3try:4    from .middleware.jwt_middleware import JWTBearer, verify_token5except ImportError:6    from app.middleware.jwt_middleware import JWTBearer, verify_token7from typing import Dict, Optional8import os9 10 11# Initialize JWT Bearer scheme12jwt_bearer_scheme = JWTBearer()13 14def get_current_user(request: Request) -> Dict:15    """16    Get current authenticated user from JWT token issued by Better Auth.17 18    This function extracts user information from the request state that was set by the JWT middleware.19    It's used as a dependency in route handlers that require authentication.20    """21    # The JWTBearer middleware has already verified the token and attached user info to the request state22    if not hasattr(request.state, 'user_id') or request.state.user_id is None:23        raise HTTPException(24            status_code=status.HTTP_401_UNAUTHORIZED,25            detail="Could not validate credentials",26            headers={"WWW-Authenticate": "Bearer"},27        )28 29    # Extract user information from the request state30    user_payload = getattr(request.state, 'user_payload', {})31 32    # You can add more user information from the payload as needed33    return {34        "user_id": request.state.user_id,35        "email": user_payload.get("email", ""),36        "name": user_payload.get("name", "")37    }38 39async def get_user_id_from_token(request: Request, _: str = Depends(jwt_bearer_scheme)) -> str:40    """41    Extract and return only the user_id from the JWT token.42 43    This function first ensures the JWT token is valid by using the JWTBearer middleware,44    then extracts the user_id from the request state that was set by the middleware.45    """46    # The JWTBearer middleware has already verified the token and attached user info to the request state47    if not hasattr(request.state, 'user_id') or request.state.user_id is None:48        raise HTTPException(49            status_code=status.HTTP_401_UNAUTHORIZED,50            detail="Invalid authentication credentials",51            headers={"WWW-Authenticate": "Bearer"},52        )53 54    return request.state.user_id55 56def verify_user_owns_resource(user_id: str, resource_user_id: str) -> bool:57    """58    Verify that the authenticated user owns a specific resource.59 60    This function checks if the user_id from the JWT token matches61    the user_id associated with a resource (e.g., a task).62    """63    return user_id == resource_user_id