Closed
Description
The FastAPI-JWT plugin provides a basic usage example which demonstrates using the Authorize: AuthJWT = Depends()
dependency to get a handle on the JWT plugin instance, and then use the Authorize.jwt_required()
function to protect endpoints.
Since we will be doing this across the application, the following utility function could wrap the entire process up and ultimately return the currently logged in user:
async def get_current_user(session:
AsyncSession = Depends(get_async_session),
Authorize: AuthJWT = Depends()
):
"""
"""
Authorize.jwt_required()
current_user_email = Authorize.get_jwt_subject()
user = await User.get_by_email(session, current_user_email)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
a demonstration of using it in the /me
endpoint
@router.get("/me",
response_model=UserResponse,
operation_id="who_am_i"
)
async def get_me(request: Request,
Authorize: AuthJWT = Depends(),
current_user = Depends(get_current_user),
session: AsyncSession = Depends(get_async_session)):
"""Get the currently logged in user or myself
This endpoint will return the currently logged in user or raise
and exception if the user is not logged in.
"""
return current_user
This example was developed as part of the first application developed using this template and we should merge these ideas into the base template