From 5122dc96d08a407204f1280172c6b8d7e3bc99b6 Mon Sep 17 00:00:00 2001 From: Chris Veilleux Date: Wed, 26 Sep 2018 22:36:44 -0500 Subject: [PATCH] moved JWT creation logic to shared package for re-usability --- shared/selene_util/auth.py | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/shared/selene_util/auth.py b/shared/selene_util/auth.py index d3dea471..5d343c11 100644 --- a/shared/selene_util/auth.py +++ b/shared/selene_util/auth.py @@ -1,7 +1,11 @@ +from datetime import datetime from logging import getLogger +from time import time import jwt +THIRTY_DAYS = 2592000 + _log = getLogger(__package__) @@ -9,13 +13,32 @@ class AuthenticationError(Exception): pass +def encode_auth_token(secret_key, user_uuid): + """ + Generates the Auth Token + :return: string + """ + token_expiration = time() + THIRTY_DAYS + payload = dict(iat=datetime.utcnow(), exp=token_expiration, sub=user_uuid) + selene_token = jwt.encode( + payload, + secret_key, + algorithm='HS256' + ) + + # before returning the token, convert it from bytes to string so that + # it can be included in a JSON response object + return selene_token.decode() + + def decode_auth_token(auth_token: str, secret_key: str) -> tuple: """ Decodes the auth token - :param auth_token: the Selene JSON Web Token extracted from the request cookies. + :param auth_token: the Selene JSON Web Token extracted from cookies. :param secret_key: the key needed to decode the token - :return: two-value tuple containing a boolean value indicating if the token is good and the - user UUID extracted from the token. UUID will be None if token is invalid. + :return: two-value tuple containing a boolean value indicating if the + token is good and the user UUID extracted from the token. UUID will + be None if token is invalid. """ try: payload = jwt.decode(auth_token, secret_key)