Skip to content

Commit

Permalink
feat(app): Attach logs into auth wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
ful1e5 committed Nov 21, 2023
1 parent 92496b5 commit b2077cc
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
2 changes: 1 addition & 1 deletion api/core/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

@app.route("/api/core/session", methods=["GET"])
def get_session():
auth = decode_auth_header()
auth = decode_auth_header(logger)

if isinstance(auth, tuple):
return auth[0], auth[1]
Expand Down
31 changes: 24 additions & 7 deletions core/utils/token.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os
from dataclasses import dataclass
from logging import Logger
from typing import Literal, Union

import jwt
Expand Down Expand Up @@ -44,23 +45,35 @@ def as_token(data) -> Union[None, AuthToken]:
return None


def decode_token(token: str):
def decode_token(token: str, logger: Union[Logger, None] = None):
try:
payload = jwt.decode(token, SECRET, algorithms=["HS256"])
auth = as_token(payload)
if auth:
return auth
else:
return "invalid"
except jwt.ExpiredSignatureError:
except jwt.ExpiredSignatureError as e:
if logger:
logger.error(
f"Expired Token: {e}\n token:{token}",
)
return "expired"
except jwt.InvalidTokenError:
except jwt.InvalidTokenError as e:
if logger:
logger.error(
f"Inavlid Token: {e}\n token:{token}",
)
return "invalid"
except Exception:
except Exception as e:
if logger:
logger.error(
f"Exception on decode: {e}\n token:{token}",
)
return "invalid"


def decode_auth_header():
def decode_auth_header(logger: Union[Logger, None] = None):
unauth = jsonify({"status": 401, "error": ["Unauthorized"]})
invalid = jsonify({"status": 401, "error": ["Invalid Token"]})
expired = jsonify({"status": 401, "error": ["Expired Token"]})
Expand All @@ -70,14 +83,18 @@ def decode_auth_header():
if auth_header and auth_header.startswith("Bearer "):
token = auth_header[len("Bearer ") :]
try:
auth = decode_token(token)
auth = decode_token(token, logger)
if auth == "expired":
return expired, 401
elif auth == "invalid":
return invalid, 401
else:
return auth
except Exception:
except Exception as e:
if logger:
logger.error(
f"Exception on parsing: {e}\n token:{token}",
)
return internal_error, 500

else:
Expand Down

0 comments on commit b2077cc

Please sign in to comment.