test_app_1 / security.py
areen09's picture
Upload 4 files
a3ecff7 verified
Raw History Blame Contribute Delete
920 Bytes
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from config import settings
# Instantiate the bearer scheme
bearer_scheme = HTTPBearer()
def verify_token(credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme)):
"""
Dependency function to verify the bearer token.
"""
if not credentials or credentials.scheme!= "Bearer":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication scheme.",
)
# The token string is in the 'credentials' attribute, not 'token'.
if credentials.credentials!= settings.API_SECRET_TOKEN:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token.",
headers={"WWW-Authenticate": "Bearer"},
)
return True