o
    ×èFh‚M  ã                   @   sÚ  d Z ddlZddlZddlZddlZddlmZ ddlmZ ddlmZ ddlm	Z	 ddl
ZddlZddlZddlmZ ddlmZ dd	lmZ d
ZdZdZdZeejdd� ¡ ƒZeejdd� ¡ ƒZeejdd� ¡ ƒZdZeg d¢ƒZdZdZ dZ!dZ"G dd„ dej#j$j%ƒZ&G dd„ dƒZ'G dd„ dƒZ(G d d!„ d!e	j)ƒZ*G d"d#„ d#ƒZ+G d$d%„ d%ƒZ,G d&d'„ d'ej-ƒZ.G d(d)„ d)ej-ƒZ/G d*d+„ d+ej0ƒZ1G d,d-„ d-ej0ƒZ2G d.d/„ d/ej3ƒZ4G d0d1„ d1e4ƒZ5G d2d3„ d3e4ƒZ6dS )4z1Firebase token minting and validation sub module.é    N)Úcredentials)Úiam)Újwt)Ú	transport)Ú
exceptions)Ú_auth_utils)Ú_http_clientzhttps://securetoken.google.com/zXhttps://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.comz$https://session.firebase.google.com/zEhttps://www.googleapis.com/identitytoolkit/v3/relyingparty/publicKeysé   )Úminutesé   )Údaysé   )ÚhourszYhttps://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit)ÚacrÚamrÚat_hashÚaudÚ	auth_timeÚazpÚcnfÚc_hashÚexpÚfirebaseÚiatÚissÚjtiÚnbfÚnonceÚsubzZhttp://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/emailÚRS256Únonez"firebase-auth-emulator@example.comc                   @   s    e Zd ZdZdd„ Zdd„ ZdS )Ú_EmulatedSignerNc                 C   s   d S ©N© ©Úselfr#   r#   úR/var/www/html/loop/nvenv/lib/python3.10/site-packages/firebase_admin/_token_gen.pyÚ__init__B   ó   z_EmulatedSigner.__init__c                 C   s   dS )Nó    r#   ©r%   Úmessager#   r#   r&   ÚsignE   r(   z_EmulatedSigner.sign)Ú__name__Ú
__module__Ú__qualname__Úkey_idr'   r,   r#   r#   r#   r&   r!   ?   s    r!   c                   @   sd   e Zd ZdZefdd„Zedd„ ƒZedd„ ƒZedd	„ ƒZ	e
d
d„ ƒZe
dd„ ƒZe
dd„ ƒZdS )Ú_SigningProviderz2Stores a reference to a google.auth.crypto.Signer.c                 C   s   || _ || _|| _d S r"   )Ú_signerÚ_signer_emailÚ_alg)r%   ÚsignerÚsigner_emailÚalgr#   r#   r&   r'   L   s   
z_SigningProvider.__init__c                 C   ó   | j S r"   )r2   r$   r#   r#   r&   r5   Q   ó   z_SigningProvider.signerc                 C   r8   r"   )r3   r$   r#   r#   r&   r6   U   r9   z_SigningProvider.signer_emailc                 C   r8   r"   )r4   r$   r#   r#   r&   r7   Y   r9   z_SigningProvider.algc                 C   s   t |j|jƒS r"   )r1   r5   r6   )ÚclsÚgoogle_credr#   r#   r&   Úfrom_credential]   ó   z _SigningProvider.from_credentialc                 C   s   t  |||¡}t||ƒS r"   )r   ÚSignerr1   )r:   Úrequestr;   Úservice_accountr5   r#   r#   r&   Úfrom_iama   s   
z_SigningProvider.from_iamc                 C   s   t tƒ ttƒS r"   )r1   r!   ÚAUTH_EMULATOR_EMAILÚALGORITHM_NONE)r:   r#   r#   r&   Úfor_emulatorf   r=   z_SigningProvider.for_emulatorN)r-   r.   r/   Ú__doc__ÚALGORITHM_RS256r'   Úpropertyr5   r6   r7   Úclassmethodr<   rA   rD   r#   r#   r#   r&   r1   I   s    




r1   c                   @   sD   e Zd ZdZdZddd„Zdd„ Zedd	„ ƒZdd
d„Z	dd„ Z
dS )ÚTokenGeneratorz,Generates custom tokens and session cookies.z)https://identitytoolkit.googleapis.com/v1Nc                 C   s<   || _ || _tj ¡ | _|p| j}d ||j¡| _	d | _
d S )Nz{0}/projects/{1})ÚappÚhttp_clientr   ÚrequestsÚRequestr?   ÚID_TOOLKIT_URLÚformatÚ
project_idÚbase_urlÚ_signing_provider)r%   rJ   rK   Úurl_overrideÚ
url_prefixr#   r#   r&   r'   p   s   

zTokenGenerator.__init__c                 C   s¸   t  ¡ rt ¡ S | jj ¡ }t|tj	j
jƒrt |¡S | jj d¡}|r,t | j||¡S t|tjƒr7t |¡S | jtddid�}|jdkrOtd |j ¡ ¡ƒ‚|j ¡ }t | j||¡S )zPInitializes a signing provider by following the go/firebase-admin-sign protocol.ÚserviceAccountIdzMetadata-FlavorÚGoogle)ÚurlÚheaderséÈ   z2Failed to contact the local metadata service: {0}.)r   Úis_emulatedr1   rD   rJ   Ú
credentialÚget_credentialÚ
isinstanceÚgoogleÚoauth2r@   ÚCredentialsr<   ÚoptionsÚgetrA   r?   r   ÚSigningÚMETADATA_SERVICE_URLÚstatusÚ
ValueErrorrO   ÚdataÚdecode)r%   r;   r@   Úrespr#   r#   r&   Ú_init_signing_providerx   s"   


ÿ
z%TokenGenerator._init_signing_providerc              
   C   sL   | j s#z	|  ¡ | _ W | j S  ty" } z
d}td ||¡ƒ‚d}~ww | j S )z@Initializes and returns the SigningProvider instance to be used.z@https://firebase.google.com/docs/auth/admin/create-custom-tokenszøFailed to determine service account: {0}. Make sure to initialize the SDK with service account credentials or specify a service account ID with iam.serviceAccounts.signBlob permission. Please refer to {1} for more details on creating custom tokens.N)rR   rj   Ú	Exceptionrf   rO   )r%   ÚerrorrW   r#   r#   r&   Úsigning_provider•   s   ùü€þzTokenGenerator.signing_providerc              
   C   s&  |dur5t |tƒstdƒ‚t| ¡ ƒt@ }|r5t|ƒdkr)d d |¡¡}t|ƒ‚d d |¡¡}t|ƒ‚|rBt |t	ƒrBt|ƒdkrFtdƒ‚| j
}tt ¡ ƒ}|j|jt|||t d	œ}|rb||d
< |durj||d< d|ji}	z
tj|j||	d�W S  tjjjy’ }
 z
d |
¡}t||
ƒ‚d}
~
ww )z.Builds and signs a Firebase custom auth token.Nz%developer_claims must be a dictionaryr   z:Developer claims {0} are reserved and cannot be specified.z, z8Developer claim {0} is reserved and cannot be specified.é€   z2uid must be a string between 1 and 128 characters.)r   r   r   Úuidr   r   Ú	tenant_idÚclaimsr7   )Úheaderz Failed to sign custom token. {0})r]   Údictrf   ÚsetÚkeysÚRESERVED_CLAIMSÚlenrO   ÚjoinÚstrrm   ÚintÚtimer6   ÚFIREBASE_AUDIENCEÚMAX_TOKEN_LIFETIME_SECONDSr7   r   Úencoder5   r^   Úauthr   ÚTransportErrorÚTokenSignError)r%   ro   Údeveloper_claimsrp   Údisallowed_keysÚerror_messagerm   ÚnowÚpayloadrr   rl   Úmsgr#   r#   r&   Úcreate_custom_token¤   sR   
ÿÿýÿÿú


€þz"TokenGenerator.create_custom_tokenc              
   C   s  t |tƒr
| d¡n|}t |tƒr|std |¡ƒ‚t |tjƒr&t| 	¡ ƒ}t |t
ƒs0t |tƒs7td |¡ƒ‚|tk rCtd |t¡ƒ‚|tkrOtd |t¡ƒ‚d | j¡}||dœ}z| jjd||d	�\}}W n tjjyz } zt |¡‚d
}~ww |r‚| d¡s‰tjd|d�‚| d¡S )z4Creates a session cookie from the provided ID token.úutf-8zDIllegal ID token provided: {0}. ID token must be a non-empty string.zIllegal expiry duration: {0}.zDIllegal expiry duration: {0}. Duration must be at least {1} seconds.zCIllegal expiry duration: {0}. Duration must be at most {1} seconds.z{0}:createSessionCookie)ÚidTokenÚvalidDurationÚpost)ÚjsonNÚsessionCookiez Failed to create session cookie.)Úhttp_response)r]   Úbytesrh   ry   rf   rO   ÚdatetimeÚ	timedeltarz   Útotal_secondsÚboolÚ#MIN_SESSION_COOKIE_DURATION_SECONDSÚ#MAX_SESSION_COOKIE_DURATION_SECONDSrQ   rK   Úbody_and_responserL   r   ÚRequestExceptionr   Úhandle_auth_backend_errorrb   ÚUnexpectedResponseError)r%   Úid_tokenÚ
expires_inrW   r†   ÚbodyÚ	http_resprl   r#   r#   r&   Úcreate_session_cookieÑ   sB   þÿÿþ
€ÿÿ
z$TokenGenerator.create_session_cookier"   )NN)r-   r.   r/   rE   rN   r'   rj   rG   rm   rˆ   rŸ   r#   r#   r#   r&   rI   k   s    


-rI   c                   @   s<   e Zd ZdZddd„Zedd„ ƒZedd„ ƒZdd
d„ZdS )ÚCertificateFetchRequestzyA google-auth transport that supports HTTP cache-control.

    Also injects a timeout to each outgoing HTTP request.
    Nc                 C   s*   t  t ¡ ¡| _tj | j¡| _|| _	d S r"   )
ÚcachecontrolÚCacheControlrL   ÚSessionÚ_sessionr   rM   ÚsessionÚ	_delegateÚ_timeout_seconds)r%   Útimeout_secondsr#   r#   r&   r'   ú   s   
z CertificateFetchRequest.__init__c                 C   r8   r"   )r¤   r$   r#   r#   r&   r¥   ÿ   r9   zCertificateFetchRequest.sessionc                 C   r8   r"   )r§   r$   r#   r#   r&   r¨     r9   z'CertificateFetchRequest.timeout_secondsÚGETc                 K   s&   |p| j }| j|f||||dœ|¤ŽS )N)Úmethodr�   rX   Útimeout)r¨   r¦   )r%   rW   rª   r�   rX   r«   Úkwargsr#   r#   r&   Ú__call__  s   
ÿÿÿz CertificateFetchRequest.__call__r"   )r©   NNN)	r-   r.   r/   rE   r'   rG   r¥   r¨   r­   r#   r#   r#   r&   r    ô   s    


r    c                   @   s,   e Zd ZdZdd„ Zd
dd„Zd
dd„Zd	S )ÚTokenVerifierz'Verifies ID tokens and session cookies.c              
   C   sX   |j  dtj¡}t|ƒ| _t|jdddtt	t
jtd�| _t|jdddttttd�| _d S )NÚhttpTimeoutzID tokenzverify_id_token()z<https://firebase.google.com/docs/auth/admin/verify-id-tokens)rP   Ú
short_nameÚ	operationÚdoc_urlÚcert_urlÚissuerÚinvalid_token_errorÚexpired_token_errorzsession cookiezverify_session_cookie())ra   rb   r   ÚDEFAULT_TIMEOUT_SECONDSr    r?   Ú_JWTVerifierrP   ÚID_TOKEN_CERT_URIÚID_TOKEN_ISSUER_PREFIXr   ÚInvalidIdTokenErrorÚExpiredIdTokenErrorÚid_token_verifierÚCOOKIE_CERT_URIÚCOOKIE_ISSUER_PREFIXÚInvalidSessionCookieErrorÚExpiredSessionCookieErrorÚcookie_verifier)r%   rJ   r«   r#   r#   r&   r'     s(   
ùùzTokenVerifier.__init__r   c                 C   ó   | j  || j|¡S r"   )r½   Úverifyr?   )r%   r›   Úclock_skew_secondsr#   r#   r&   Úverify_id_token$  ó   zTokenVerifier.verify_id_tokenc                 C   rÃ   r"   )rÂ   rÄ   r?   )r%   ÚcookierÅ   r#   r#   r&   Úverify_session_cookie'  rÇ   z#TokenVerifier.verify_session_cookieN©r   )r-   r.   r/   rE   r'   rÆ   rÉ   r#   r#   r#   r&   r®     s
    
r®   c                   @   s*   e Zd ZdZdd„ Zd
dd„Zdd„ Zd	S )r¸   z6Verifies Firebase JWTs (ID tokens or session cookies).c                 K   s”   |  d¡| _|  d¡| _|  d¡| _|  d¡| _|  d¡| _|  d¡| _| jd  ¡ dv r5d	 | j¡| _	nd
 | j¡| _	|  d¡| _
|  d¡| _d S )NrP   r°   r±   r²   r³   r´   r   Úaeiouzan {0}za {0}rµ   r¶   )ÚpoprP   r°   r±   rW   r³   r´   ÚlowerrO   Úarticled_short_nameÚ_invalid_token_errorÚ_expired_token_error)r%   r¬   r#   r#   r&   r'   .  s   z_JWTVerifier.__init__r   c              
   C   sÀ  t |tƒr
| d¡n|}t |tƒr|std | j|¡ƒ‚| js'td | j¡ƒ‚|dk s/|dkr6td |¡ƒ‚|  	|¡\}}| 
d¡}| 
d¡}| 
d	¡}| j| j }	d
 | j¡}
d | j| j¡}t ¡ }d}|tkrsd | j| j¡}nŠ|s | 
d¡s | 
d¡dkr™| 
d¡dkr™d| 
di ¡v r™d | j| j¡}ndd | j¡}n]|sµ| 
d¡dkrµd | j| 
d¡|¡}nH|| jkrÆd | j| j||
|¡}n7||	krÕd | j|	||
|¡}n(|du sÞt |tƒsæd | j|¡}n|sðd | j|¡}nt|ƒdkrýd | j|¡}|�r|  |¡‚z|�r|}ntjjj||| j| j|d�}|d	 |d< |W S  tjjj�y: } ztt|ƒ|d�‚d}~w t�y_ } zd t|ƒv �rR| jt|ƒ|d�‚| jt|ƒ|d�‚d}~ww )!z5Verifies the signature and data for the provided JWT.r‰   z:Illegal {0} provided: {1}. {0} must be a non-empty string.a  Failed to ascertain project ID from the credential or the environment. Project ID is required to call {0}. Initialize the app with a credentials.Certificate or set your Firebase project ID as an app option. Alternatively set the GOOGLE_CLOUD_PROJECT environment variable.r   é<   zKIllegal clock_skew_seconds value: {0}. Must be between 0 and 60, inclusive.r   r   r   zlMake sure the {0} comes from the same Firebase project as the service account used to authenticate this SDK.z+See {0} for details on how to retrieve {1}.Nz.{0} expects {1}, but was given a custom token.Úkidr7   ÚHS256Úvro   Údz5{0} expects {1}, but was given a legacy custom token.z Firebase {0} has no "kid" claim.r   zIFirebase {0} has incorrect algorithm. Expected "RS256" but got "{1}". {2}zXFirebase {0} has incorrect "aud" (audience) claim. Expected "{1}" but got "{2}". {3} {4}zVFirebase {0} has incorrect "iss" (issuer) claim. Expected "{1}" but got "{2}". {3} {4}z.Firebase {0} has no "sub" (subject) claim. {1}z;Firebase {0} has an empty string "sub" (subject) claim. {1}rn   zHFirebase {0} has a "sub" (subject) claim longer than 128 characters. {1})r?   ÚaudienceÚ	certs_urlÚclock_skew_in_seconds©ÚcausezToken expired)r]   ry   r~   r�   rf   rO   r°   rP   r±   Ú_decode_unverifiedrb   r´   rW   r   rZ   r|   rÎ   rw   rÏ   r^   r_   r›   Úverify_tokenr³   r   r   r€   ÚCertificateFetchErrorrÐ   )r%   Útokenr?   rÅ   rr   r†   r´   rÖ   ÚsubjectÚexpected_issuerÚproject_id_match_msgÚverify_id_token_msgÚemulatedr„   Úverified_claimsrl   r#   r#   r&   rÄ   <  s¼   
þüþ


þÿþÿÿþþ
ÿþ
ÿþ
þ
þ
þ
û€€ýz_JWTVerifier.verifyc              
   C   sN   zt  |¡}t j|dd�}||fW S  ty& } z	| jt|ƒ|d�‚d }~ww )NF)rÄ   rÙ   )r   Údecode_headerrh   rf   rÏ   ry   )r%   rÞ   rr   r†   rl   r#   r#   r&   rÛ   œ  s   

€ÿz_JWTVerifier._decode_unverifiedNrÊ   )r-   r.   r/   rE   r'   rÄ   rÛ   r#   r#   r#   r&   r¸   +  s
    
`r¸   c                   @   ó   e Zd ZdZdd„ ZdS )r�   z7Unexpected error while signing a Firebase custom token.c                 C   ó   t j | ||¡ d S r"   ©r   ÚUnknownErrorr'   ©r%   r+   rÚ   r#   r#   r&   r'   ¨  ó   zTokenSignError.__init__N©r-   r.   r/   rE   r'   r#   r#   r#   r&   r�   ¥  ó    r�   c                   @   ræ   )rÝ   zHFailed to fetch some public key certificates required to verify a token.c                 C   rç   r"   rè   rê   r#   r#   r&   r'   ¯  rë   zCertificateFetchError.__init__Nrì   r#   r#   r#   r&   rÝ   ¬  rí   rÝ   c                   @   ræ   )r¼   z!The provided ID token is expired.c                 C   rç   r"   ©r   r»   r'   rê   r#   r#   r&   r'   ¶  rë   zExpiredIdTokenError.__init__Nrì   r#   r#   r#   r&   r¼   ³  rí   r¼   c                   @   ræ   )ÚRevokedIdTokenErrorz'The provided ID token has been revoked.c                 C   s   t j | |¡ d S r"   rî   r*   r#   r#   r&   r'   ½  rÇ   zRevokedIdTokenError.__init__Nrì   r#   r#   r#   r&   rï   º  rí   rï   c                   @   s   e Zd ZdZddd„ZdS )rÀ   z;The provided string is not a valid Firebase session cookie.Nc                 C   rç   r"   )r   ÚInvalidArgumentErrorr'   rê   r#   r#   r&   r'   Ä  rë   z"InvalidSessionCookieError.__init__r"   rì   r#   r#   r#   r&   rÀ   Á  s    rÀ   c                   @   ræ   )rÁ   z'The provided session cookie is expired.c                 C   s   t  | ||¡ d S r"   ©rÀ   r'   rê   r#   r#   r&   r'   Ë  rÇ   z"ExpiredSessionCookieError.__init__Nrì   r#   r#   r#   r&   rÁ   È  rí   rÁ   c                   @   ræ   )ÚRevokedSessionCookieErrorz-The provided session cookie has been revoked.c                 C   s   t  | |¡ d S r"   rñ   r*   r#   r#   r&   r'   Ò  s   z"RevokedSessionCookieError.__init__Nrì   r#   r#   r#   r&   rò   Ï  rí   rò   )7rE   r‘   r{   r¡   rL   Úgoogle.authr   r   r   r   Úgoogle.auth.exceptionsr^   Úgoogle.oauth2.id_tokenÚgoogle.oauth2.service_accountÚfirebase_adminr   r   r   rº   r¹   r¿   r¾   rz   r’   r“   r•   r–   r}   r|   rt   rv   rd   rF   rC   rB   r   Úcryptr>   r!   r1   rI   rM   r    r®   r¸   ré   r�   rÝ   r»   r¼   rï   rð   rÀ   rÁ   rò   r#   r#   r#   r&   Ú<module>   sT   
" 
z