Skip to content

Instantly share code, notes, and snippets.

@an01f01
Created July 14, 2022 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save an01f01/a5626d36c5279332f802830b4f5e5b8c to your computer and use it in GitHub Desktop.
Save an01f01/a5626d36c5279332f802830b4f5e5b8c to your computer and use it in GitHub Desktop.
def encode_auth_token(user_id):
"""
Generates the Auth Token that expires in 365 days
:return: string
"""
try:
payload = {
'exp': datetime.datetime.utcnow() + datetime.timedelta(days=365, seconds=0),
'iat': datetime.datetime.utcnow(),
'sub': user_id
}
return jwt.encode(
payload,
os.environ['BOOKS_SECRET'],
algorithm='HS256'
)
except Exception as e:
return e
def decode_auth_token(auth_token):
"""
Decodes the auth token
:param auth_token:
:return: { 'success': < 0 if sucess, otherwise < 0 is a fail >, 'user': <user name>, 'message': <message> }
"""
try:
payload = jwt.decode(auth_token, os.environ['BOOKS_SECRET'], algorithms=["HS256"])
return { 'success': 0, 'user': payload['sub'], 'message': '' }
except jwt.ExpiredSignatureError:
return { 'success': -1, 'user': None, 'message': 'Signature expired. Please log in again.' }
except jwt.InvalidTokenError:
return { 'success': -2, 'user': None, 'message': 'Invalid token. Please log in again.' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment