Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
53 changed files
with
488 additions
and
347 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
# Standard Library | ||
from typing import Any, Dict, Optional | ||
|
||
# Third Party | ||
from fastapi.exceptions import HTTPException as FastAPIHTTPException | ||
|
||
|
||
class HTTPException(FastAPIHTTPException): | ||
def __init__( | ||
self, | ||
status_code: int, | ||
detail: Any = None, | ||
user_flag: bool = False, | ||
headers: Optional[Dict[str, Any]] = None, | ||
) -> None: | ||
super().__init__(status_code=status_code, detail=detail, headers=headers) | ||
self.user_flag = user_flag |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
# Standard Library | ||
from datetime import datetime, timedelta | ||
|
||
# Third Party | ||
import jwt | ||
from loguru import logger | ||
|
||
# Local | ||
from bel.Config import config | ||
|
||
jwt_algorithm = "HS256" | ||
|
||
|
||
def jwt_create(userid, payload, expiration=None): | ||
"""Create a JSON Web Token | ||
payload: dictionary to be added to JWT | ||
expiration: number of seconds from now to expire token -- defaults to 3600 seconds | ||
""" | ||
|
||
if expiration: | ||
exp = datetime.utcnow() + timedelta(seconds=expiration) | ||
else: | ||
exp = datetime.utcnow() + timedelta(seconds=3600) | ||
|
||
additional_payload = { | ||
"sub": userid, | ||
"exp": exp, | ||
"iat": datetime.utcnow(), | ||
} | ||
|
||
logger.debug("UserId: ", userid, " Payload: ", payload) | ||
|
||
payload.update(additional_payload) | ||
token = jwt.encode( | ||
payload, config["secrets"]["bel_api"]["shared_secret"], algorithm=jwt_algorithm | ||
) | ||
|
||
return token.decode("utf-8") | ||
|
||
|
||
def jwt_validate(token): | ||
"""Validates JSON Web Token | ||
Returns: | ||
valid: boolean - true if valid token | ||
token_payload: dict of token payload | ||
""" | ||
try: | ||
jwt.decode(token, config["secrets"]["bel_api"]["shared_secret"], algorithm=jwt_algorithm) | ||
return True | ||
except Exception as e: | ||
return False | ||
|
||
|
||
def jwt_extract(token): | ||
logger.debug("In JWT Extract") | ||
try: | ||
return ( | ||
jwt.decode( | ||
token, config["secrets"]["bel_api"]["shared_secret"], algorithm=jwt_algorithm | ||
), | ||
"", | ||
) | ||
except jwt.ExpiredSignatureError: | ||
logger.debug("JWT expired") | ||
return None, "JWT expired" | ||
except Exception as e: | ||
logger.debug("JWT extraction error ", e) | ||
return None, e |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
# Standard Library | ||
import re | ||
import time | ||
|
||
# Third Party | ||
from loguru import logger | ||
from starlette.middleware.base import BaseHTTPMiddleware | ||
|
||
|
||
@logger.catch | ||
class StatsMiddleware(BaseHTTPMiddleware): | ||
"""Get duration of request""" | ||
|
||
async def dispatch(self, request, call_next): | ||
|
||
url = str(request.url) | ||
method = str(request.method) | ||
t0 = time.time() | ||
|
||
response = await call_next(request) | ||
|
||
url = url.rstrip("/") | ||
route_name = url.split("/")[-1] | ||
|
||
# logger.info("Skipping status/metrics", url=url, route_name=route_name) | ||
|
||
if method == "OPTIONS" or route_name in ["status", "metrics", "ping"]: | ||
return response | ||
else: | ||
t1 = time.time() | ||
|
||
duration = f"{(t1 - t0) * 1000:.0f}" | ||
|
||
logger.opt(exception=True).info( | ||
"Request Metrics {duration_ms} ms, status_code: {status_code} {method} {url}", | ||
# "Request Metrics {duration_ms} ms, status_code: {status_code}", | ||
duration_ms=duration, | ||
status_code=response.status_code, | ||
method=method, | ||
url=url, | ||
) | ||
|
||
return response |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.