
    ]hM                        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      j1                               Z e ej.                  d      j1                               Z e ej.                  d      j1                               ZdZ eg d      ZdZdZ dZ!dZ" G d dejF                  jH                  jJ                        Z& G d d      Z' G d d      Z( G d  d!e	jR                        Z* G d" d#      Z+ G d$ d%      Z, G d& d'ejZ                        Z. G d( d)ejZ                        Z/ G d* d+ej`                        Z1 G d, d-ej`                        Z2 G d. d/ejf                        Z4 G d0 d1e4      Z5 G d2 d3e4      Z6y)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                       e Zd ZdZd Zd Zy)_EmulatedSignerNc                      y N selfs    _/var/www/html/Kila-kolis-project/venv/lib/python3.12/site-packages/firebase_admin/_token_gen.py__init__z_EmulatedSigner.__init__B   s        c                      y)Nr+   r&   r(   messages     r)   signz_EmulatedSigner.signE   s    r+   )__name__
__module____qualname__key_idr*   r/   r&   r+   r)   r#   r#   ?   s    Fr+   r#   c                   z    e Zd ZdZefdZed        Zed        Zed        Z	e
d        Ze
d        Ze
d        Zy	)
_SigningProviderz2Stores a reference to a google.auth.crypto.Signer.c                 .    || _         || _        || _        y r%   )_signer_signer_email_alg)r(   signersigner_emailalgs       r)   r*   z_SigningProvider.__init__L   s    )	r+   c                     | j                   S r%   )r7   r'   s    r)   r:   z_SigningProvider.signerQ   s    ||r+   c                     | j                   S r%   )r8   r'   s    r)   r;   z_SigningProvider.signer_emailU   s    !!!r+   c                     | j                   S r%   )r9   r'   s    r)   r<   z_SigningProvider.algY   s    yyr+   c                 B    t        |j                  |j                        S r%   )r5   r:   r;   )clsgoogle_creds     r)   from_credentialz _SigningProvider.from_credential]   s     2 2K4L4LMMr+   c                 H    t        j                  |||      }t        ||      S r%   )r   Signerr5   )rA   requestrB   service_accountr:   s        r)   from_iamz_SigningProvider.from_iama   s!    G[/B88r+   c                 <    t        t               t        t              S r%   )r5   r#   AUTH_EMULATOR_EMAILALGORITHM_NONE)rA   s    r)   for_emulatorz_SigningProvider.for_emulatorf   s     13FWWr+   N)r0   r1   r2   __doc__ALGORITHM_RS256r*   propertyr:   r;   r<   classmethodrC   rH   rL   r&   r+   r)   r5   r5   I   s    <1@ 
   " "   N N 9 9 X Xr+   r5   c                   @    e Zd ZdZdZd	dZd Zed        Zd
dZ	d Z
y)TokenGeneratorz,Generates custom tokens and session cookies.z)https://identitytoolkit.googleapis.com/v1Nc                     || _         || _        t        j                  j	                         | _        |xs | j                  }dj                  ||j                        | _	        d | _
        y )Nz{0}/projects/{1})apphttp_clientr   requestsRequestrF   ID_TOOLKIT_URLformat
project_idbase_url_signing_provider)r(   rT   rU   url_override
url_prefixs        r)   r*   zTokenGenerator.__init__p   sW    & ))113!8T%8%8
*11*cnnM!%r+   c                 8   t        j                         rt        j                         S | j                  j
                  j                         }t        |t        j                  j                  j                        rt        j                  |      S | j                  j                  j                  d      }|r!t        j                  | j                   ||      S t        |t"        j$                        rt        j                  |      S | j!                  t&        ddi      }|j(                  dk7  r2t+        dj-                  |j.                  j1                                     |j.                  j1                         }t        j                  | 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_emulatedr5   rL   rT   
credentialget_credential
isinstancegoogleoauth2rG   CredentialsrC   optionsgetrH   rF   r   SigningMETADATA_SERVICE_URLstatus
ValueErrorrY   datadecode)r(   rB   rG   resps       r)   _init_signing_providerz%TokenGenerator._init_signing_providerx   s9   ""$#0022hh))88:k6==#@#@#L#LM#33K@@ ((**../AB#,,T\\;XX k;#6#67#33K@@ || 4?PRZ>[|\;;#DKKDIIL\L\L^_a a))**,(({OTTr+   c                     | j                   s"	 | j                         | _         | j                   S | j                   S # t        $ r"}d}t        dj	                  ||            d}~ww xY w)z@Initializes and returns the SigningProvider instance to be used.z@https://firebase.google.com/docs/auth/admin/create-custom-tokenszFailed 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)r\   ru   	Exceptionrq   rY   )r(   errorrb   s      r)   signing_providerzTokenGenerator.signing_provider   sy     %%M)-)D)D)F& %%%t%%%  MX 9 :@s9K	M MMs   ; 	A&A!!A&c                 V   |t        |t              st        d      t        |j	                               t
        z  }|rdt        |      dkD  r+dj                  dj                  |            }t        |      dj                  dj                  |            }t        |      |rt        |t              rt        |      dkD  rt        d      | j                  }t        t        j                               }|j                  |j                  t        |||t        z   d	}|r||d
<   |||d<   d|j                   i}		 t#        j$                  |j&                  ||	      S # t(        j*                  j,                  j.                  $ r"}
dj                  |
      }t1        ||
      d}
~
ww xY 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claimsr<   )headerz Failed to sign custom token. {0})rh   dictrq   setkeysRESERVED_CLAIMSlenrY   joinstrry   inttimer;   FIREBASE_AUDIENCEMAX_TOKEN_LIFETIME_SECONDSr<   r   encoder:   ri   authr   TransportErrorTokenSignError)r(   r|   developer_claimsr}   disallowed_keyserror_messagery   nowpayloadr   rx   msgs               r)   create_custom_tokenz"TokenGenerator.create_custom_token   s   '.5 !HII!"2"7"7"9:_LO'!+&<<BF)-?)C=E " !//&<<BF)-?)C=E " !//*S#.#c(S.QRR00$))+#00#00$33
 #,GK ' 0GH)--.	-::.55wvNN{{%%44 	-4;;EBC e,,	-s   =!E 'F(F##F(c                    t        |t              r|j                  d      n|}t        |t              r|st	        dj                  |            t        |t        j                        rt        |j                               }t        |t              st        |t              st	        dj                  |            |t        k  rt	        dj                  |t                    |t        kD  rt	        dj                  |t                    dj                  | j                        }||d}	 | j                  j                  d||	      \  }}|r|j!                  d
      st#        j$                  d|      |j!                  d
      S # t&        j(                  j*                  $ r}t#        j,                  |      d}~ww xY w)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)jsonsessionCookiez Failed to create session cookie.)http_responseN)rh   bytesrs   r   rq   rY   datetime	timedeltar   total_secondsbool#MIN_SESSION_COOKIE_DURATION_SECONDS#MAX_SESSION_COOKIE_DURATION_SECONDSr[   rU   body_and_responserm   r   UnexpectedResponseErrorrV   r   RequestExceptionhandle_auth_backend_error)r(   id_token
expires_inrb   r   body	http_resprx   s           r)   create_session_cookiez$TokenGenerator.create_session_cookie   s   /9(E/J8??7+PX(C( &*, , j("4"45Z5578Jj$'z*c/J<CCJOPP;; ((.z;^(_a a;; ((.z;^(_a a (..t}}='
	-"..@@SZ@[OD) txx8!996iQ Q88O,, ""33 	?77>>	?s   .!F
 
G'F<<Gr%   )NN)r0   r1   r2   rM   rX   r*   ru   rO   ry   r   r   r&   r+   r)   rR   rR   k   s4    6@N&U: & &*-Z -r+   rR   c                   @    e Zd ZdZddZed        Zed        ZddZy)	CertificateFetchRequestzyA google-auth transport that supports HTTP cache-control.

    Also injects a timeout to each outgoing HTTP request.
    Nc                     t        j                  t        j                               | _        t
        j                  j                  | j                        | _        || _	        y r%   )
cachecontrolCacheControlrV   Session_sessionr   rW   session	_delegate_timeout_seconds)r(   timeout_secondss     r)   r*   z CertificateFetchRequest.__init__   sA    $11(2B2B2DE"++33DLLA /r+   c                     | j                   S r%   )r   r'   s    r)   r   zCertificateFetchRequest.session   s    }}r+   c                     | j                   S r%   )r   r'   s    r)   r   z'CertificateFetchRequest.timeout_seconds  s    $$$r+   c                 R    |xs | j                   } | j                  |f||||d|S )N)methodr   rc   timeout)r   r   )r(   rb   r   r   rc   r   kwargss          r)   __call__z CertificateFetchRequest.__call__  sB    1T11t~~WT7GWOUW 	Wr+   r%   )GETNNN)	r0   r1   r2   rM   r*   rO   r   r   r   r&   r+   r)   r   r      s:    
0
   % %Wr+   r   c                   &    e Zd ZdZd ZddZddZy)TokenVerifierz'Verifies ID tokens and session cookies.c           
      T   |j                   j                  dt        j                        }t	        |      | _        t        |j                  dddt        t        t        j                  t              | _        t        |j                  dddt        t        t         t"              | _        y )NhttpTimeoutzID tokenzverify_id_token()z<https://firebase.google.com/docs/auth/admin/verify-id-tokens)rZ   
short_name	operationdoc_urlcert_urlissuerinvalid_token_errorexpired_token_errorzsession cookiezverify_session_cookie())rl   rm   r	   DEFAULT_TIMEOUT_SECONDSr   rF   _JWTVerifierrZ   ID_TOKEN_CERT_URIID_TOKEN_ISSUER_PREFIXr   InvalidIdTokenErrorExpiredIdTokenErrorid_token_verifierCOOKIE_CERT_URICOOKIE_ISSUER_PREFIXInvalidSessionCookieErrorExpiredSessionCookieErrorcookie_verifier)r(   rT   r   s      r)   r*   zTokenVerifier.__init__  s    ++//-1U1UV.w7!-~~*)R&) + ? ? 3"5  ,~~2B/R$' 9 9 ;r+   c                 P    | j                   j                  || j                  |      S r%   )r   verifyrF   )r(   r   clock_skew_secondss      r)   verify_id_tokenzTokenVerifier.verify_id_token$  s"    %%,,Xt||EWXXr+   c                 P    | j                   j                  || j                  |      S r%   )r   r   rF   )r(   cookier   s      r)   verify_session_cookiez#TokenVerifier.verify_session_cookie'  s"    ##**64<<ASTTr+   Nr   )r0   r1   r2   rM   r*   r   r   r&   r+   r)   r   r     s    1;(YUr+   r   c                   $    e Zd ZdZd ZddZd Zy)r   z6Verifies Firebase JWTs (ID tokens or session cookies).c                 $   |j                  d      | _        |j                  d      | _        |j                  d      | _        |j                  d      | _        |j                  d      | _        |j                  d      | _        | j                  d   j                         dv r!d	j                  | j                        | _	        n d
j                  | j                        | _	        |j                  d      | _
        |j                  d      | _        y )NrZ   r   r   r   r   r   r   aeiouzan {0}za {0}r   r   )poprZ   r   r   rb   r   r   lowerrY   articled_short_name_invalid_token_error_expired_token_error)r(   r   s     r)   r*   z_JWTVerifier.__init__.  s     **\2 **\2K0::i(

:.jj*??1##%0'/t'GD$'.~~doo'FD$$*JJ/D$E!$*JJ/D$E!r+   c                 ~   t        |t              r|j                  d      n|}t        |t              r|s%t	        dj                  | j                  |            | j                  s$t	        dj                  | j                              |dk  s|dkD  rt	        dj                  |            | j                  |      \  }}|j                  d      }|j                  d      }|j                  d	      }| j                  | j                  z   }	d
j                  | j                        }
dj                  | j                  | j                        }t        j                         }d}|t        k(  r(dj                  | j                  | j                         }n|s|j                  d      s|j                  d      dk(  rP|j                  d      dk(  r<d|j                  di       v r(dj                  | j                  | j                         }n6dj                  | j                        }n|sA|j                  d      dk7  r-dj                  | j                  |j                  d      |      }n|| j                  k7  r*dj                  | j                  | j                  ||
|      }n||	k7  r dj                  | j                  |	||
|      }nx|t        |t              sdj                  | j                  |      }nI|sdj                  | j                  |      }n*t#        |      dkD  rdj                  | j                  |      }|r| j%                  |      	 |r|}nBt&        j(                  j*                  j-                  ||| j                  | j.                  |      }|d	   |d<   |S # t&        j0                  j2                  j4                  $ r}t7        t        |      |      d}~wt        $ rJ}d t        |      v r| j9                  t        |      |      | j%                  t        |      |      d}~ww xY 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.kidr<   HS256vr|   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}r{   zHFirebase {0} has a "sub" (subject) claim longer than 128 characters. {1})rF   audience	certs_urlclock_skew_in_secondscausezToken expired)rh   r   r   r   rq   rY   r   rZ   r   _decode_unverifiedrm   r   rb   r   re   r   r   r   r   ri   rj   r   verify_tokenr   r   r   r   CertificateFetchErrorr   )r(   tokenrF   r   r   r   r   r   subjectexpected_issuerproject_id_match_msgverify_id_token_msgemulatedr   verified_claimsrx   s                   r)   r   z_JWTVerifier.verify<  s   )3E3)?W%U%'u &%8: : = >DVDNN=S	U U !%7"%<]*+- - 11%8U#;;u%++e$++7((.t(? 	 :@@4??[ 	 **,((0H0HI  &**U"3zz% G+11"'7;;sB+?"?#VDNND4L4LM  !C I I$// Zfjj/7:#VDOOVZZ5FH[\  (%%+VDOOT__h,@BU&W  &%%+VDOO_f,@BU&W  _Jw$<fT__.AB  fT__.AB  \CfT__.AB  ++M::	E")"(--"8"8"E"E#!__"mm*< #F #> &5U%;OE"""{{%%44 	A'E
%@@ 	E#e*,//E
%/HH++CJe+DD	Es&   AN) )'P<O&&P<2AP77P<c                     	 t        j                  |      }t        j                  |d      }||fS # t        $ r!}| j	                  t        |      |      d }~ww xY w)NF)r   r   )r   decode_headerrs   rq   r   r   )r(   r   r   r   rx   s        r)   r   z_JWTVerifier._decode_unverified  s^    	E&&u-Fjju5G7?" 	E++CJe+DD	Es   /2 	AAANr   )r0   r1   r2   rM   r*   r   r   r&   r+   r)   r   r   +  s    @F^E@Er+   r   c                       e Zd ZdZd Zy)r   z7Unexpected error while signing a Firebase custom token.c                 F    t         j                  j                  | ||       y r%   r   UnknownErrorr*   r(   r.   r   s      r)   r*   zTokenSignError.__init__      ((w>r+   Nr0   r1   r2   rM   r*   r&   r+   r)   r   r     s
    A?r+   r   c                       e Zd ZdZd Zy)r   zHFailed to fetch some public key certificates required to verify a token.c                 F    t         j                  j                  | ||       y r%   r  r  s      r)   r*   zCertificateFetchError.__init__  r  r+   Nr  r&   r+   r)   r   r     s
    R?r+   r   c                       e Zd ZdZd Zy)r   z!The provided ID token is expired.c                 F    t         j                  j                  | ||       y r%   r   r   r*   r  s      r)   r*   zExpiredIdTokenError.__init__  s    ''00wFr+   Nr  r&   r+   r)   r   r     s    +Gr+   r   c                       e Zd ZdZd Zy)RevokedIdTokenErrorz'The provided ID token has been revoked.c                 D    t         j                  j                  | |       y r%   r
  r-   s     r)   r*   zRevokedIdTokenError.__init__  s    ''00w?r+   Nr  r&   r+   r)   r  r    s    1@r+   r  c                       e Zd ZdZddZy)r   z;The provided string is not a valid Firebase session cookie.Nc                 F    t         j                  j                  | ||       y r%   )r   InvalidArgumentErrorr*   r  s      r)   r*   z"InvalidSessionCookieError.__init__  s    ''00wFr+   r%   r  r&   r+   r)   r   r     s    EGr+   r   c                       e Zd ZdZd Zy)r   z'The provided session cookie is expired.c                 2    t         j                  | ||       y r%   r   r*   r  s      r)   r*   z"ExpiredSessionCookieError.__init__  s    !**4%@r+   Nr  r&   r+   r)   r   r     s    1Ar+   r   c                       e Zd ZdZd Zy)RevokedSessionCookieErrorz-The provided session cookie has been revoked.c                 0    t         j                  | |       y r%   r  r-   s     r)   r*   z"RevokedSessionCookieError.__init__  s    !**49r+   Nr  r&   r+   r)   r  r    s
    7:r+   r  )7rM   r   r   r   rV   google.authr   r   r   r   google.auth.exceptionsri   google.oauth2.id_tokengoogle.oauth2.service_accountfirebase_adminr   r   r	   r   r   r   r   r   r   r   r   r   r   r   r   r   ro   rN   rK   rJ   r   cryptrE   r#   r5   rR   rW   r   r   r   r  r   r   r   r   r  r  r   r   r  r&   r+   r)   <module>r     s   8     #   !   $ % & ' ; >  > Y&)*<(*<*<Q*G*U*U*W&X #&)*<(*<*<"*E*S*S*U&V # !!3!3!3!!<!J!J!LM C   9  ; fkk''.. X XDF- F-RWi// W2U U<wE wEt?Z,, ??J33 ?G+99 G@+99 @G
 ? ? GA 9 A: 9 :r+   