From 38966ea1956691406afc130e4dc4af54c32b23c7 Mon Sep 17 00:00:00 2001 From: Dev Mukherjee Date: Mon, 6 Mar 2023 15:24:59 +1100 Subject: [PATCH] refactor: moves to using user id in jwt payload REFS #52 previous implementation of the jwt subject was using email based on examples where the users always login with email + passwords. the template allows for OTP based logins where by the user may not have an email for an extended period of time, this refactors to the subject being set to using the user.id --- src/labs/routers/auth/__init__.py | 7 +++++-- src/labs/routers/utils.py | 8 ++++---- src/labs/schema/auth.py | 2 +- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/labs/routers/auth/__init__.py b/src/labs/routers/auth/__init__.py index b8ceaaa..c55cc93 100644 --- a/src/labs/routers/auth/__init__.py +++ b/src/labs/routers/auth/__init__.py @@ -40,7 +40,10 @@ async def login_for_auth_token( """ Attempt to authenticate a user and issue JWT token """ - user = await User.get_by_email(session, form_data.username) + user = await User.get_by_email( + session, + form_data.username + ) if user is None or not user.check_password(form_data.password): raise HTTPException( @@ -50,7 +53,7 @@ async def login_for_auth_token( ) access_token = create_access_token( - subject=user.email, + subject=user.id, fresh=True ) diff --git a/src/labs/routers/utils.py b/src/labs/routers/utils.py index 7a6afa4..6232c63 100644 --- a/src/labs/routers/utils.py +++ b/src/labs/routers/utils.py @@ -38,17 +38,17 @@ async def get_current_user( algorithms=[config.JWT_ALGORITHM] ) - username: str = payload.get("sub") + user_id: str = payload.get("sub") - if username is None: + if user_id is None: raise credentials_exception - token_data = TokenData(username=username) + token_data = TokenData(id=user_id) except: raise credentials_exception - user = await User.get_by_email(session, token_data.username) + user = await User.get(session, token_data.id) if user is None: raise credentials_exception diff --git a/src/labs/schema/auth.py b/src/labs/schema/auth.py index 157efcc..f170d57 100644 --- a/src/labs/schema/auth.py +++ b/src/labs/schema/auth.py @@ -16,7 +16,7 @@ class TokenData(BaseModel): is a valid token. """ - username: str = None + id: str = None class SignupRequest(AppBaseModel):