Model/backend/app/dependencies.py
Khalim Conn-Kowlessar 271fb9de3a Setting up jwt auth
2023-07-06 11:52:38 +01:00

60 lines
1.9 KiB
Python

from fastapi import Depends, HTTPException, status
from fastapi.security import APIKeyHeader, OAuth2PasswordBearer
from app.config import get_settings
api_key_header = APIKeyHeader(name=get_settings().API_KEY_NAME, auto_error=False)
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
async def validate_api_key(api_key_header: str = Depends(api_key_header)):
if api_key_header != get_settings().API_KEY:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail="Could not validate credentials"
)
return api_key_header
from jose import jwt, JWTError
from fastapi import HTTPException, status
from typing import Optional
SECRET_KEY = "YOUR_SECRET_KEY"
ALGORITHM = "HS256"
def get_user(user_id: str):
# Define here how to fetch a user from your database
# using the user_id. Here's a simple placeholder implementation:
user = None
if user_id == "known_id":
user = {"id": user_id, "name": "Known User"}
return user
def validate_jwt_token(token: str = Depends(oauth2_scheme)):
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])
user_id: str = payload.get("sub")
if user_id is None:
raise credentials_exception
user = get_user(user_id=user_id)
if user is None:
raise credentials_exception
return user
except JWTError:
raise credentials_exception
async def validate_token(token: str = Depends(oauth2_scheme)):
if get_settings().ENV != "local":
token_data = validate_jwt_token(token)
if not token_data:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail="Could not validate credentials"
)
return token