From f4ba4d9d18bcedf3852a1c5f23b550c0416f71f8 Mon Sep 17 00:00:00 2001 From: Matt <77928207+mattzcarey@users.noreply.github.com> Date: Wed, 5 Jul 2023 08:27:58 +0100 Subject: [PATCH] fix: jwt decode to return user object (#513) --- backend/auth/auth_bearer.py | 2 +- backend/auth/jwt_token_handler.py | 13 ++++--------- 2 files changed, 5 insertions(+), 10 deletions(-) diff --git a/backend/auth/auth_bearer.py b/backend/auth/auth_bearer.py index c5034f7f1..4f0c9d5bd 100644 --- a/backend/auth/auth_bearer.py +++ b/backend/auth/auth_bearer.py @@ -56,5 +56,5 @@ class AuthBearer(HTTPBearer): ) # replace with test user information -def get_current_user(user: dict = Depends(AuthBearer())) -> User: +def get_current_user(user: User = Depends(AuthBearer())) -> User: return user diff --git a/backend/auth/jwt_token_handler.py b/backend/auth/jwt_token_handler.py index 6975c7893..43b287500 100644 --- a/backend/auth/jwt_token_handler.py +++ b/backend/auth/jwt_token_handler.py @@ -4,6 +4,7 @@ from typing import Optional from jose import jwt from jose.exceptions import JWTError +from models.users import User SECRET_KEY = os.environ.get("JWT_SECRET_KEY") ALGORITHM = "HS256" @@ -20,23 +21,17 @@ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None): return encoded_jwt -def decode_access_token(token: str): +def decode_access_token(token: str) -> User: try: payload = jwt.decode( token, SECRET_KEY, algorithms=[ALGORITHM], options={"verify_aud": False} ) - return payload except JWTError: return None + return User(email=payload.get("email"), id=payload.get("sub")) + def verify_token(token: str): payload = decode_access_token(token) return payload is not None - - -def get_user_email_from_token(token: str): - payload = decode_access_token(token) - if payload: - return payload.get("email") - return "none"