1
+ from typing import Optional , Any
2
+ from fastapi import Request
3
+ from jose import jwt , JWTError
1
4
from posthog import Posthog
2
5
3
6
from app .config import config
@@ -14,12 +17,31 @@ def initialize_posthog() -> None:
14
17
posthog_client = Posthog (project_api_key = token , host = host )
15
18
16
19
17
- def capture_exception (exc : Exception ) -> None :
20
+ def _get_email_from_request (request : Request ) -> Optional [str ]:
21
+ auth = request .headers .get ("Authorization" )
22
+ if not auth or not auth .startswith ("Bearer " ) or not config .SECRET_KEY :
23
+ return None
24
+ token = auth .split (" " , 1 )[1 ]
25
+ try :
26
+ payload = jwt .decode (token , config .SECRET_KEY , algorithms = ["HS256" ])
27
+ except JWTError :
28
+ return None
29
+ return payload .get ("sub" )
30
+
31
+
32
+ def capture_exception (exc : Exception , request : Optional [Request ] = None ) -> None :
18
33
"""Capture an exception with PostHog if initialized."""
19
34
if posthog_client is None :
20
35
return
36
+
37
+ kwargs : dict [str , Any ] = {}
38
+ if request is not None :
39
+ email = _get_email_from_request (request )
40
+ if email :
41
+ kwargs ["distinct_id" ] = email
42
+ kwargs ["properties" ] = {"email" : email } # TODO: decouple
21
43
try :
22
- posthog_client .capture_exception (exc )
44
+ posthog_client .capture_exception (exc , ** kwargs )
23
45
except Exception :
24
46
# Avoid raising exceptions from PostHog itself
25
- pass
47
+ pass
0 commit comments