aboutsummaryrefslogtreecommitdiff
path: root/api/util/authentication.py
diff options
context:
space:
mode:
authorParker <contact@pkrm.dev>2024-11-04 21:00:42 -0600
committerParker <contact@pkrm.dev>2024-11-04 21:00:42 -0600
commitd4280d1fda2f4809274793e7bd49f484f57a883e (patch)
tree23085015b92d916d304968b396df8edceca037c5 /api/util/authentication.py
parent8ae8c5c454ba42e8f56f415d33bbaaac7d1a37ec (diff)
Continue JWT implementation - add refresh token
Diffstat (limited to 'api/util/authentication.py')
-rw-r--r--api/util/authentication.py22
1 files changed, 15 insertions, 7 deletions
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