fix: jwt decode to return user object (#513)

This commit is contained in:
Matt 2023-07-05 08:27:58 +01:00 committed by GitHub
parent 02272ab0ca
commit f4ba4d9d18
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 5 additions and 10 deletions

View File

@ -56,5 +56,5 @@ class AuthBearer(HTTPBearer):
) # replace with test user information ) # 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 return user

View File

@ -4,6 +4,7 @@ from typing import Optional
from jose import jwt from jose import jwt
from jose.exceptions import JWTError from jose.exceptions import JWTError
from models.users import User
SECRET_KEY = os.environ.get("JWT_SECRET_KEY") SECRET_KEY = os.environ.get("JWT_SECRET_KEY")
ALGORITHM = "HS256" ALGORITHM = "HS256"
@ -20,23 +21,17 @@ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
return encoded_jwt return encoded_jwt
def decode_access_token(token: str): def decode_access_token(token: str) -> User:
try: try:
payload = jwt.decode( payload = jwt.decode(
token, SECRET_KEY, algorithms=[ALGORITHM], options={"verify_aud": False} token, SECRET_KEY, algorithms=[ALGORITHM], options={"verify_aud": False}
) )
return payload
except JWTError: except JWTError:
return None return None
return User(email=payload.get("email"), id=payload.get("sub"))
def verify_token(token: str): def verify_token(token: str):
payload = decode_access_token(token) payload = decode_access_token(token)
return payload is not None 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"