refactor(chalice): auth logging

This commit is contained in:
Taha Yassine Kraiem 2024-05-09 11:45:38 +02:00 committed by rjshrjndrn
parent c304a727a8
commit c673e9c7cc

View file

@ -1,3 +1,4 @@
import logging
from typing import Optional
from fastapi import Request
@ -5,8 +6,10 @@ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from starlette import status
from starlette.exceptions import HTTPException
from chalicelib.core import authorizers, users
import schemas_ee
from chalicelib.core import authorizers, users
logger = logging.getLogger(__name__)
class JWTAuth(HTTPBearer):
@ -18,28 +21,32 @@ class JWTAuth(HTTPBearer):
if credentials:
if not credentials.scheme == "Bearer":
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid authentication scheme.")
logging.debug("----------------------------------JWT auth")
jwt_payload = authorizers.jwt_authorizer(scheme=credentials.scheme, token=credentials.credentials)
logging.debug(jwt_payload)
auth_exists = jwt_payload is not None \
and users.auth_exists(user_id=jwt_payload.get("userId", -1),
tenant_id=jwt_payload.get("tenantId", -1),
jwt_iat=jwt_payload.get("iat", 100),
jwt_aud=jwt_payload.get("aud", ""))
logging.debug(f"auth exists: {auth_exists}")
if jwt_payload is None \
or jwt_payload.get("iat") is None or jwt_payload.get("aud") is None \
or not auth_exists:
if jwt_payload is not None:
print(jwt_payload)
logging.warning(jwt_payload)
if jwt_payload.get("iat") is None:
print("JWTAuth: iat is None")
logging.warning("JWTAuth: iat is None")
if jwt_payload.get("aud") is None:
print("JWTAuth: aud is None")
logging.warning("JWTAuth: aud is None")
if not auth_exists:
print("JWTAuth: not users.auth_exists")
logging.warning("JWTAuth: not users.auth_exists")
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid token or expired token.")
user = users.get(user_id=jwt_payload.get("userId", -1), tenant_id=jwt_payload.get("tenantId", -1))
logging.debug(f"user: {user}")
if user is None:
print("JWTAuth: User not found.")
logging.warning("JWTAuth: User not found.")
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User not found.")
jwt_payload["authorizer_identity"] = "jwt"
request.state.authorizer_identity = "jwt"
@ -53,5 +60,5 @@ class JWTAuth(HTTPBearer):
return request.state.currentContext
else:
print("JWTAuth: Invalid authorization code.")
logging.warning("JWTAuth: Invalid authorization code.")
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid authorization code.")