
    䟾h                         S r SSKrSSKJr  SSKJrJr  SSKrSSKJ	r	  SSK
Jr  \R                  " \5      rS\S\4S	 jrS
 rg)z8
Middleware for handling user context in Flask requests
    Nwraps)requestg)JWT_SECRET_KEY)LangSmithUserContexttokenreturnc                 X    [         R                  " U [        S/S9nUR                  S5      UR                  S5      S.$ ! [         R                   a    [
        R                  S5         g[         R                   a+  n[
        R                  S[        U5       35         SnAgSnAff = f)	z'Extract user information from JWT tokenHS256)
algorithmsuser_idemail)idr   zToken has expiredNzInvalid token: )	jwtdecoder   getExpiredSignatureErrorloggerwarningInvalidTokenErrorstr)r	   payloades      AD:\Projects\AI-TestCaseGenerator\utils\user_context_middleware.pyget_user_from_tokenr      s    **UNyI++i([[)
 	
 $$ *+   Q12s   =A   )B)+B)>!B$$B)c                 0   ^  [        T 5      U 4S j5       nU$ )z)Decorator to add user context to requestsc                    > [         R                  R                  S5      nU(       a  UR                  S5      (       d  [        R                  S5        T" U 0 UD6$ UR                  S5      S   n[        U5      nU(       d  [        R                  S5        T" U 0 UD6$ U[        l	        [        US   US   S	9   T" U 0 UD6sS S S 5        $ ! , (       d  f       g = f)
NAuthorizationzBearer z#No valid Authorization header found    z!Could not extract user from tokenr   r   )r   
user_email)r   headersr   
startswithr   r   splitr   r   userr   )argskwargsauth_headerr	   r&   fs        r   decorated_function-with_user_context.<locals>.decorated_function   s     oo))/:+"8"8"C"CNN@Ad%f%%!!#&q)"5)NN>?d%f%%  "$t*gOd%f% POOs   9C
Cr   )r*   r+   s   ` r   with_user_contextr-      s!    
1X& &*     )__doc__logging	functoolsr   flaskr   r   r   config.settingsr   utils.langsmith_contextr   	getLogger__name__r   r   dictr   r-    r.   r   <module>r9      sF       
 * 8			8	$s t r.   