From d4280d1fda2f4809274793e7bd49f484f57a883e Mon Sep 17 00:00:00 2001 From: Parker Date: Mon, 4 Nov 2024 21:00:42 -0600 Subject: Continue JWT implementation - add refresh token --- api/util/authentication.py | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) (limited to 'api/util/authentication.py') diff --git a/api/util/authentication.py b/api/util/authentication.py index 4dfbc77..507b806 100644 --- a/api/util/authentication.py +++ b/api/util/authentication.py @@ -41,7 +41,6 @@ def authenticate_user(db, username: str, password: str): If so, return the user object """ user = get_user(db, username) - print(user) if not user: return False if not verify_password(password, user.hashed_password): @@ -49,22 +48,21 @@ def authenticate_user(db, username: str, password: str): return user -def create_access_token(data: dict, expires_delta: timedelta | None = None): +def create_access_token(data: dict, expires_delta: timedelta): """ Return an encoded JWT token with the given data """ to_encode = data.copy() - if expires_delta: - expire = datetime.utcnow() + expires_delta - else: - expire = datetime.utcnow() + timedelta(minutes=15) + expire = datetime.utcnow() + expires_delta to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, secret_key, algorithm=algorithm) return encoded_jwt async def get_current_user( - token: Annotated[str, Depends(oauth2_scheme)], db=Depends(get_db) + token: Annotated[str, Depends(oauth2_scheme)], + is_refresh: bool = False, + db=Depends(get_db), ): """ Return the current user based on the token, or raise a 401 error @@ -77,8 +75,18 @@ async def get_current_user( try: payload = jwt.decode(token, secret_key, algorithms=[algorithm]) username: str = payload.get("sub") + refresh: bool = payload.get("refresh") if username is None: raise credentials_exception + # For some reason, an access token was passed when a refresh + # token was expected - some likely malicious activity + if not refresh and is_refresh: + raise credentials_exception + # If the token passed is a refresh token and the function + # is not expecting a refresh token, raise an error + if refresh and not is_refresh: + raise credentials_exception + token_data = TokenData(username=username) except InvalidTokenError: raise credentials_exception -- cgit v1.2.3-70-g09d2