
    [i)Q                    R   U d dl mZ d dlZd dlZd dlmZmZ d dlmZmZm	Z	 d dl
mZmZmZmZmZ d dlmZmZ d dlmZ d dlmZ d d	lmZ d d
lmZmZ  ee      Zded<   er G d de      ZdZ ded<   dZ!ded<    e"e!      Z#ded<   dZ$ded<   dZ%ded<    G d d      Z&d,dZ'd-dZ(d.dZ)d/dZ*d0dZ+d1dZ,d1d Z-	 d2	 	 	 	 	 	 	 	 	 d3d!Z.d4d"Z/d5d#Z0d6d$Z1	 	 	 	 	 	 	 	 	 	 d7d%Z2	 	 	 	 	 	 d8d&Z3	 	 	 	 	 	 	 	 	 	 d9d'Z4 ejj                  d(      Z6	 	 	 	 	 	 d:d)Z7	 	 	 	 	 	 	 	 d;d*Z8d<d+Z9y)=    )annotationsN)CallableMapping)datetime	timedeltatimezone)TYPE_CHECKINGAnyFinal	TypedDictcast)	urlencodeurlparse)config)StreamlitAuthError)
get_logger)AttrDictsecrets_singletonr   _LOGGERc                  "    e Zd ZU ded<   ded<   y)ProviderTokenPayloadstrproviderintexpN)__name__
__module____qualname____annotations__     d/var/www/html/userprofiledev.eatanceapp.com/venv/lib/python3.12/site-packages/streamlit/auth_util.pyr   r   !   s    r!   r   i   MAX_COOKIE_BYTESz; Path=/; HttpOnlyCOOKIE_ATTRIBUTESCOOKIE_ATTR_SIZE2   SIGNING_OVERHEAD_SAFETY_BUFFER   SINGLE_BYTE_BASE64_SIZEc                  :    e Zd ZdZddZd	dZd
ddZddZddZy)	AuthCachezBSimple cache implementation for storing info required for Authlib.c                    i | _         y Ncacheselfs    r"   __init__zAuthCache.__init__4   s	    %'
r!   c                8    | j                   j                  |      S r-   )r/   getr1   keys     r"   r4   zAuthCache.get7   s    zz~~c""r!   Nc                "    || j                   |<   y r-   r.   )r1   r6   value
expires_ins       r"   setzAuthCache.set<   s    

3r!   c                    | j                   S r-   r.   r0   s    r"   get_dictzAuthCache.get_dict?   s    zzr!   c                <    | j                   j                  |d        y r-   )r/   popr5   s     r"   deletezAuthCache.deleteB   s    

sD!r!   )returnNone)r6   r   r@   r
   r-   )r6   r   r8   r
   r9   z
int | Noner@   rA   )r@   dict[str, Any])r6   r   r@   rA   )	r   r   r   __doc__r2   r4   r:   r<   r?   r    r!   r"   r+   r+   1   s    L(#
 "r!   r+   c                     	 ddl } | j                  }t        t        t        |j                  d                  }|dk  ry	 y# t        t        f$ r Y yw xY w)zCheck if Authlib is installed.r   N.)         FT)authlib__version__tuplemapr   splitImportErrorModuleNotFoundError)rI   authlib_versionauthlib_version_tuples      r"   is_authlib_installedrR   F   sa    	!-- %c#/D/DS/I&J K 9, -  ,- s   =A AAc                     t        j                  d      } t        j                         r)t        j                  d      }|r|j	                  d|       } | S )zEGet the cookie signing secret from the configuration or secrets.toml.zserver.cookieSecretauthcookie_secret)r   
get_optionr   load_if_toml_existsr4   )signing_secretauth_sections     r"   get_signing_secretrZ   U   sJ     ++,ABN,,.(,,V4)--o~NNr!   c            	         t        i       } t        j                         r)t        dt        j                  dt        i                   } | S )z+Get the 'auth' section of the secrets.toml.r   rT   )r   r   rW   r   r4   )rY   s    r"   get_secrets_auth_sectionr\   _   s;    B<L,,.J(9(=(=fhrl(STr!   c                     t               } | j                  d      }t        |t              r|g}n+t        |t              r|D cg c]  }t        |       }}ng S t        |      ddhz
  rt        d      |S c c}w )zGet the expose_tokens configuration from secrets.toml.

    Returns a list of token types to expose. Accepts both string and list formats:
    - expose_tokens = "id" -> ["id"]
    - expose_tokens = ["id", "access"] -> ["id", "access"]
    expose_tokensidaccesszHInvalid expose_tokens configuration. Only 'id' and 'access' are allowed.)r\   r4   
isinstancer   listr:   r   )rY   r^   restokens       r"   get_expose_tokens_configre   h   s     ,-L $$_5M-%o	M4	('45}es5z}5	
3x4"" V
 	
 J 6s   A8c                    d| vry| d   }d|v r.|j                  dt        t        j                  d                  }	 t	        |      }|j                         S # t
        $ r t        d| d      w xY w)zJGet the redirect_uri from auth_section - filling in port number if needed.redirect_uriNz{port}zserver.portzInvalid redirect_uri: ". Please check your configuration.)replacer   r   rV   r   
ValueErrorr   geturlrY   rg   redirect_uri_parseds      r"   get_redirect_urirn      s     \)$^4L<#++c&++M:;

&|4 %%''  
 $\N2TU
 	

s   A A2c                     t               } | syt        |       }|sy|j                  d      st        j	                  d       y|S )a6  Get the redirect_uri from secrets, validating it ends with /oauth2callback.

    This is used for logout flows where we need a validated redirect URI
    that matches the OAuth callback path.

    Returns
    -------
    str | None
        The validated redirect URI, or None if not configured or invalid.
    Nz/oauth2callbackz.Redirect URI does not end with /oauth2callback)r\   rn   endswithr   warning)rY   rg   s     r"   get_validated_redirect_urirr      sG     ,-L#L1L  !23HIr!   c                     t               } | syt        |       }|syt        |      }|j                   d|j                   S )zExtract the origin (scheme + host) from the configured redirect_uri.

    Returns
    -------
    str | None
        The origin in format "scheme://host:port", or None if not configured.
    Nz://)r\   rn   r   schemenetlocrl   s      r"   get_origin_from_redirect_urirv      sM     ,-L#L1L"<0!(()-@-G-G,HIIr!   c                    ddl m} ||d}|r||d<   t        |       }t         ||j                              }i ||}t        |      }	|j                  |	      j                         S )a  Build an OIDC logout URL with the required parameters.

    Parameters
    ----------
    end_session_endpoint
        The OIDC provider's end_session_endpoint URL.
    client_id
        The OAuth client ID.
    post_logout_redirect_uri
        The URI to redirect to after logout.
    id_token
        Optional ID token to include as id_token_hint for the logout request.

    Returns
    -------
    str
        The complete logout URL with query parameters.
    r   )	parse_qsl)	client_idpost_logout_redirect_uriid_token_hint)query)urllib.parserx   r   dictr|   r   _replacerk   )
end_session_endpointry   rz   id_tokenrx   logout_paramsparsedexisting_paramsmerged_params	new_querys
             r"   build_logout_urlr      sx    0 ' $<%M
 )1o& *+F9V\\23O88-8M-(I???+2244r!   c                   	 ddl m} ddi}| t	        j
                  t        j                        t        d      z   d	}|j                  ||t                     }|j                  d
      S # t        $ r t        d      dw xY w)zAReturns a signed JWT token with the provider and expiration time.r   )jwtcTo use authentication features, you need to install Authlib>=1.3.2, e.g. via `pip install Authlib`.NalgHS256rH   )minutes)r   r   zlatin-1)authlib.joser   rN   r   r   nowr   utcr   encoderZ   decode)r   r   headerpayloadprovider_tokens        r"   encode_provider_tokenr      s    $ WF||HLL)Ia,@@G  JJvw8J8LMN  ++   u
	s   A+ +Bc                   	 ddl m}m}m} ddiddid}	 |j                  | t               |      }|j                          t        d
|      S # t        $ r t        d      dw xY w# |$ r}t        d	|       dd}~ww xY w)z-Decode the JWT token and validate the claims.r   )	JoseError	JWTClaimsr   r   N	essentialT)r   r   )claims_optionszError decoding provider token: r   )
r   r   r   r   rN   r   r   rZ   validater   )r   r   r   r   claim_optionsr   es          r"   decode_provider_tokenr     s    :: )$/k4=PQMR ZZ.0 ( 
 	 &00!   u
	  R #B1#!FGTQRs"   
A ,A' A$'B ,A;;B c           	        i }| j                  d      r| j                  d      |d<   | j                  d      r| j                  d      |d<   | j                  d      r| j                  d      |d<   | j                  d      r6t        d| j                  dt        i                   j                         |d<   | j                  d      r| j                  d      |d<   |S )zKGenerate a default provider section for the 'auth' section of secrets.toml.ry   client_secretserver_metadata_urlclient_kwargsr   r^   )r4   r   r   to_dict)rY   default_provider_sections     r"   !generate_default_provider_sectionr     s    !$0<0@0@0M -(4@4D4D_4U 1-.:F:J:J!;
 !67 (48(((2,G5

') 	!1 (4@4D4D_4U 1##r!   c                    t        j                  |      } |||      }t        |      dz   t        |      z   t        z   }|t        kD  r%t
        j                  d|       t        | |||       y | ||       y)a[  Set a cookie, splitting into multiple cookies if necessary.

    Args:
        set_single_cookie_fn: Function to set a single cookie (cookie_name, value)
        create_signed_value_fn: Function to create a signed cookie value (cookie_name, value)
        cookie_name: Name of the cookie
        value: Dictionary value to serialize and store
    rF   zNCookie size (%d bytes) exceeds browser limit. Splitting into multiple cookies.N)jsondumpslenr%   r#   r   debug_set_split_cookie)set_single_cookie_fncreate_signed_value_fncookie_namer8   serialized_cookie_valuesigned_valueactual_cookie_sizes          r"   set_cookie_with_chunksr   .  s     #jj/ *+7NOL [)A-L0AADTT ,,\	
 	 "#		
 	[*ABr!   c                <    d} | ||      }t        |      t        z
  S )a  Calculate the server's signing overhead by measuring the size difference.

    This empirically measures the overhead added by the signing function (e.g., Tornado's
    create_signed_value) by signing a minimal test value and computing the difference.

    Args:
        create_signed_value_fn: Function to create a signed cookie value
        cookie_name: Name of the cookie (affects overhead due to length prefix)

    Returns
    -------
        The number of bytes added by signing (excluding the base64-encoded value)
    x)r   r)   )r   r   
test_valuesigneds       r"   _calculate_signing_overheadr   T  s%    " J#K<Fv;000r!   c                   t        ||      t        z   }t        t        |      z
  dz
  t        z
  }||z
  }|t
        k  rt        d      |dz  dz  }g }t        dt        |      |      D ]  }	||	|	|z    }
|j                  |
        t        |      dk(  r | ||d          y | |dt        |              t        t        |            D ]  }	| d|	dz    } | |||	           t        j                  d	|t        |             y)
a  Split a large cookie value into multiple smaller cookies.

    The main cookie always exists and either contains the whole value or the chunk count.
    Additional chunks are stored as cookie_name_1, cookie_name_2, etc.

    Args:
        set_single_cookie_fn: Function to set a single cookie (cookie_name, value)
        create_signed_value_fn: Function to create a signed cookie value
        cookie_name: Name of the cookie
        value: Serialized string value to split and store
    rF   z0Not enough space available for the signed value.rG   r(   r   Nzchunks-_z Split cookie '%s' into %d chunks)r   r'   r#   r   r%   r)   r   rangeappendr   info)r   r   r   r8   signing_overheadavailable_for_signed_valueavailable_for_base64_value
chunk_sizechunksichunk
chunk_names               r"   r   r   j  s1   & 	$$:KH
(	)  	3{++a/2BB 
 "<>N!N "$;; !STT -q0Q6JF1c%j*-a!j.)e . 6{a[&)4 F}&=> 3v;#}Aa!eW-
Z3   LL*Fr!   s   chunks-(\d+)c                    | |      }||S t         j                  |      }||S 	 t        |j                  d            }g }t        |      D ]C  }| d|dz    } | |      }|t        j                  d|dz   |        y|j                  |       E dj                  |      }	|	S # t        t
        f$ r t        j                  d|       Y yw xY w)a  Get a cookie, reconstructing from chunks if it was split.

    If a count cookie exists, the main cookie contains the first chunk,
    and additional chunks are in cookie_name_1, cookie_name_2, etc.
    If no count cookie exists, the main cookie contains the entire value.

    Args:
        get_single_cookie_fn: Function to get a single cookie (cookie_name) -> bytes | None
        cookie_name: Name of the cookie

    Returns
    -------
        Cookie value as bytes, or None if not found
    NrF   z#Invalid chunk count for cookie '%s'r   z Missing chunk %d for cookie '%s'r!   )_chunks_regexmatchr   grouprj   	TypeErrorr   	exceptionr   errorr   join)
get_single_cookie_fnr   cookie_valuer   chunk_countr   r   r   chunk_valuereconstructed_values
             r"   get_cookie_with_chunksr     s    $ (4L-E}%++a.) F;#}Aa!eW-
*:6MM<a!e[Qk"   ((6*! 	" ?Ms   B' '%CCc                     | |      } ||       |yt         j                  |      }|y	 t        |j                  d            }t	        d|dz         D ]  } || d|         y# t
        t        f$ r Y yw xY w)a  Clear a cookie and any associated chunk cookies.

    The main cookie always exists. If there are chunks, also clear
    cookie_name_1, cookie_name_2, etc., and the count cookie.

    Args:
        get_single_cookie_fn: Function to get a single cookie (cookie_name) -> bytes | None
        clear_single_cookie_fn: Function to clear a single cookie (cookie_name)
        cookie_name: Name of the cookie
    NrF   r   )r   r   r   r   r   rj   r   )r   clear_single_cookie_fnr   r   r   r   r   s          r"   clear_cookie_and_chunksr     s     (4L;'-E}%++a.)q+/*A"k]!A3#78 +	"  	s   ;A) )A;:A;c                8   t        j                         st        d      t        j                  d      }|t        d      d|vrt        d      d|vrt        d      |j                  |       }d| v rt        d	|  d
      || dk(  rt	        |      }|| dk(  rt        d      t        d|  d      t        |t              st        d|  d      g d}|D cg c]	  }||vs| }}|r&| dk(  rt        d| d      t        d|  d| d      yc c}w )z[Validate the general auth credentials and auth credentials for the given
    provider.
    zTo use authentication features you need to configure credentials for at
            least one authentication provider in `.streamlit/secrets.toml`.rT   Nrg   zAuthentication credentials in `.streamlit/secrets.toml` are missing the
            "redirect_uri" key. Please check your configuration.rU   zAuthentication credentials in `.streamlit/secrets.toml` are missing the
            "cookie_secret" key. Please check your configuration.r   zAuth provider name "zI" contains an underscore. Please use a provider name without underscores.defaultzAuthentication credentials in `.streamlit/secrets.toml` are missing for
                the default authentication provider. Please check your configuration.zeAuthentication credentials in `.streamlit/secrets.toml` are missing for the authentication provider "z#". Please check your configuration.zYAuthentication credentials in `.streamlit/secrets.toml` for the authentication provider "z6" must be valid TOML. Please check your configuration.)ry   r   r   zAuthentication credentials in `.streamlit/secrets.toml` for the default authentication provider are missing the following keys: rh   z"" are missing the following keys: )r   rW   r   r4   r   ra   r   )r   rY   provider_sectionrequired_keysr6   missing_keyss         r"   validate_auth_credentialsr     s    002 O
 	

 %((0L O
 	
 \) D
 	
 l* E
 	

 $''1 h "8* -> ?
 	

 H	$9<\Jy $Y  !,,4: 6
 	
 &0 ((0z 2"#
 	
 JM#0P=CC?O4OC=LPy $S. BD 
 !((0z1Sn>@
 	
  Qs   	D(D)r@   bool)r@   r   )r@   r   )r@   z	list[str])rY   r   r@   
str | None)r@   r   r-   )
r   r   ry   r   rz   r   r   r   r@   r   )r   r   r@   r   )r   r   r@   r   )rY   r   r@   rB   )
r   Callable[[str, str], None]r   Callable[[str, str], bytes]r   r   r8   rB   r@   rA   )r   r   r   r   r@   r   )
r   r   r   r   r   r   r8   r   r@   rA   )r   Callable[[str], bytes | None]r   r   r@   zbytes | None)r   r   r   zCallable[[str], None]r   r   r@   rA   )r   r   r@   rA   ):
__future__r   r   recollections.abcr   r   r   r   r   typingr	   r
   r   r   r   r}   r   r   	streamlitr   streamlit.errorsr   streamlit.loggerr   streamlit.runtime.secretsr   r   r   r   r   r   r#   r$   r   r%   r'   r)   r+   rR   rZ   r\   re   rn   rr   rv   r   r   r   r   r   r   r   compiler   r   r   r   r    r!   r"   <module>r      s   #  	 - 2 2 = = ,  / ' AH% %y 
  % / 5 //0 % 0 )+  *!"  "" "*2(,4J0  	(5(5(5 "(5 	(5
 	(5V,&1.$(#C4#C7#C #C 	#C
 
#CL1711 	1,<4<7< < 	<
 
<~ 

+,-7-- -` 7 1    
	 FH
r!   