77import traceback
88import uuid
99from datetime import datetime , timezone
10- from typing import Any , Dict , Tuple
10+ from typing import Any , Dict , Optional , Tuple
1111
1212import compat_stubs # noqa: F401 - must be first
1313
@@ -126,6 +126,21 @@ def before_request() -> None:
126126 f"[{ g .request_id } ] { request .method } { request .url } - IP: { request .remote_addr } "
127127 )
128128
129+ def _safe_jwt_identity () -> Optional [str ]:
130+ """Best-effort JWT identity lookup for audit logging.
131+
132+ get_jwt_identity() raises if the current request's JWT was never
133+ successfully verified (missing, malformed, or expired token) - which
134+ is expected for anonymous or failed-auth requests, not an error
135+ worth logging. Swallowing just that lookup (rather than the whole
136+ audit_service.log_api_request(...) call, as before) keeps the audit
137+ trail intact for every request, including failed-auth ones.
138+ """
139+ try :
140+ return get_jwt_identity ()
141+ except Exception :
142+ return None
143+
129144 @app .after_request
130145 def after_request (response : Any ) -> Any :
131146 if hasattr (g , "start_time" ):
@@ -143,12 +158,7 @@ def after_request(response: Any) -> Any:
143158 response_time_ms = int (response_time ),
144159 ip_address = request .remote_addr ,
145160 user_agent = request .headers .get ("User-Agent" ),
146- user_id = (
147- get_jwt_identity ()
148- if hasattr (request , "headers" )
149- and "Authorization" in request .headers
150- else None
151- ),
161+ user_id = _safe_jwt_identity (),
152162 )
153163 except Exception as e :
154164 app .logger .error (f"Failed to create audit log: { e } " )
0 commit comments