From 89e7e38cb6e0b5993374f864b9a93d60c43888a2 Mon Sep 17 00:00:00 2001 From: Aidan Kim Date: Sun, 17 Nov 2024 19:48:57 -0500 Subject: [PATCH] FastAPI auth tutorial --- backend/api/authentication.py | 27 +++++++++++++++++++++++++++ backend/main.py | 6 +++--- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/backend/api/authentication.py b/backend/api/authentication.py index e69de29..84b97fb 100644 --- a/backend/api/authentication.py +++ b/backend/api/authentication.py @@ -0,0 +1,27 @@ +from typing import Annotated + +from fastapi import APIRouter, Depends +from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm + +from backend.models.user_model import User + +api = APIRouter(prefix="/api/auth") + +openapi_tags = { + "name": "Authentication", + "description": "Authentication and authorization handling.", +} + +oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") + +def decode_token(token): + """To implement later. Payload for JWT will be a User object returned by this function.""" + return token + +async def get_user(token: Annotated[str, Depends(oauth2_scheme)]): + user = decode_token(token) + return user + +@api.get("/user") +async def get_subject(subject: Annotated[User, Depends(get_user)]): + return subject \ No newline at end of file diff --git a/backend/main.py b/backend/main.py index 12ecaad..24a5107 100644 --- a/backend/main.py +++ b/backend/main.py @@ -3,7 +3,7 @@ from fastapi.responses import JSONResponse from fastapi.middleware.gzip import GZipMiddleware -from .api import user, health, service, resource, tag +from .api import user, health, service, resource, authentication description = """ Welcome to the **COMPASS** RESTful Application Programming Interface. @@ -18,13 +18,13 @@ app = FastAPI( health.openapi_tags, service.openapi_tags, resource.openapi_tags, - tag.openapi_tags + authentication.openapi_tags, ], ) app.add_middleware(GZipMiddleware) -feature_apis = [user, health, service, resource, tag] +feature_apis = [user, health, service, resource, authentication] for feature_api in feature_apis: app.include_router(feature_api.api)