wL iIddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z m Z m Z mZmZmZmZddlmZddlmZddlmZmZej2eZe rddlZe Gdd Ze Gd d Ze Gd d Zedddde fdZ!dddeefdZ"ddde ddfdZ#dddde ddfdZ$ddde fdZ%dddde de fdZ&de fdZ'dde dee e e ffdZ(y)N) dataclass) TYPE_CHECKINGDictListLiteralOptionalTupleUnion) constants)whoami) experimental get_tokenceZdZUdZeed<eed<eed<eed<eed<dZeeed<dZ eeed <dZ ee e d ed <y) OAuthOrgInfoa Information about an organization linked to a user logged in with OAuth. Attributes: sub (`str`): Unique identifier for the org. OpenID Connect field. name (`str`): The org's full name. OpenID Connect field. preferred_username (`str`): The org's username. OpenID Connect field. picture (`str`): The org's profile picture URL. OpenID Connect field. is_enterprise (`bool`): Whether the org is an enterprise org. Hugging Face field. can_pay (`Optional[bool]`, *optional*): Whether the org has a payment method set up. Hugging Face field. role_in_org (`Optional[str]`, *optional*): The user's role in the org. Hugging Face field. security_restrictions (`Optional[List[Literal["ip", "token-policy", "mfa", "sso"]]]`, *optional*): Array of security restrictions that the user hasn't completed for this org. Possible values: "ip", "token-policy", "mfa", "sso". Hugging Face field. subnamepreferred_usernamepicture is_enterpriseNcan_pay role_in_org)ipz token-policymfassosecurity_restrictions) __name__ __module__ __qualname____doc__str__annotations__boolrrrrrr\/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/huggingface_hub/_oauth.pyrrs[, H I L"GXd^"!%K#%Y]8D1S)T$UV]r%rceZdZUdZeed<eed<eed<eeed<eeed<eed<eed<eeed <eed <eeed <eee ed <y ) OAuthUserInfoa Information about a user logged in with OAuth. Attributes: sub (`str`): Unique identifier for the user, even in case of rename. OpenID Connect field. name (`str`): The user's full name. OpenID Connect field. preferred_username (`str`): The user's username. OpenID Connect field. email_verified (`Optional[bool]`, *optional*): Indicates if the user's email is verified. OpenID Connect field. email (`Optional[str]`, *optional*): The user's email address. OpenID Connect field. picture (`str`): The user's profile picture URL. OpenID Connect field. profile (`str`): The user's profile URL. OpenID Connect field. website (`Optional[str]`, *optional*): The user's website URL. OpenID Connect field. is_pro (`bool`): Whether the user is a pro user. Hugging Face field. can_pay (`Optional[bool]`, *optional*): Whether the user has a payment method set up. Hugging Face field. orgs (`Optional[List[OrgInfo]]`, *optional*): List of organizations the user is part of. Hugging Face field. rrremail_verifiedemailrprofilewebsiteis_prororgsN) rrrr r!r"rr#rrr$r%r&r(r(8s`8 H ITN" C= L L c] L d^ 4 % &&r%r(c^eZdZUdZeed<ej ed<eed<eeed<eed<y) OAuthInfoa Information about the OAuth login. Attributes: access_token (`str`): The access token. access_token_expires_at (`datetime.datetime`): The expiration date of the access token. user_info ([`OAuthUserInfo`]): The user information. state (`str`, *optional*): State passed to the OAuth provider in the original request to the OAuth provider. scope (`str`): Granted scope. access_tokenaccess_token_expires_at user_infostatescopeN) rrrr r!r"datetimer(rr$r%r&r0r0cs0 %... C= Jr%r0appzfastapi.FastAPI route_prefixc ddlm}tjxsddz}|j |t j|jjdd |jd }tjd #tjd t|| ytjdt!|| y#t$r}td|d}~wwxYw)a Add OAuth endpoints to a FastAPI app to enable OAuth login with Hugging Face. How to use: - Call this method on your FastAPI app to add the OAuth endpoints. - Inside your route handlers, call `parse_huggingface_oauth(request)` to retrieve the OAuth info. - If user is logged in, an [`OAuthInfo`] object is returned with the user's info. If not, `None` is returned. - In your app, make sure to add links to `/oauth/huggingface/login` and `/oauth/huggingface/logout` for the user to log in and out. Example: ```py from huggingface_hub import attach_huggingface_oauth, parse_huggingface_oauth # Create a FastAPI app app = FastAPI() # Add OAuth endpoints to the FastAPI app attach_huggingface_oauth(app) # Add a route that greets the user if they are logged in @app.get("/") def greet_json(request: Request): # Retrieve the OAuth info from the request oauth_info = parse_huggingface_oauth(request) # e.g. OAuthInfo dataclass if oauth_info is None: return {"msg": "Not logged in!"} return {"msg": f"Hello, {oauth_info.user_info.preferred_username}!"} ``` r)SessionMiddlewarezCannot initialize OAuth to due a missing library. Please run `pip install huggingface_hub[oauth]` or add `huggingface_hub[oauth]` to your requirements.txt file in order to install the required dependencies.Nz-v1noneT) secret_key same_site https_only/SPACE_IDz3OAuth is enabled in the Space. Adding OAuth routes.r8z:App is not running in a Space. Adding mocked OAuth routes.)starlette.middleware.sessionsr: ImportErrorr OAUTH_CLIENT_SECRETadd_middlewarehashlibsha256encode hexdigeststriposgetenvloggerinfo_add_oauth_routes_add_mocked_oauth_routes)r7r8r:esession_secrets r&attach_huggingface_oauthrT|sJC  339rUBN>>."7"7"9:DDF  %%c*L yy( IJ#L9 PQ <@3  t  sC C) C$$C)requestzfastapi.RequestreturncHd|jvrtjdytjd|jd}|jdi}|jdg}|r|Dcgc]}t |jd|jd|jd |jd |jd |jd |jd |jdc}nd}t |jd|jd|jd |jd|jd|jd |jd|jd|jd|jd | }t |jdtjj|jd||jd|jdScc}w)a Returns the information from a logged in user as a [`OAuthInfo`] object. For flexibility and future-proofing, this method is very lax in its parsing and does not raise errors. Missing fields are set to `None` without a warning. Return `None`, if the user is not logged in (no info in session cookie). See [`attach_huggingface_oauth`] for an example on how to use this method. oauth_infozNo OAuth info in session.Nz Parsing OAuth info from session.userinfor.rrrr isEnterprisecanPay roleInOrgsecurityRestrictions)rrrrrrrrr)r*r+r,isPro) rrrr)r*rr+r,r-rr.r1 expires_atr4r5)r1r2r3r4r5) sessionrNdebuggetrr(r0r6 fromtimestamp)rU oauth_data user_data orgs_dataorgr.r3s r&parse_huggingface_oauthrhs7??* 01 LL34.Jz2.I fb)I !  GGENWWV_#&77+?#@ *!ggn5)GGK0&)gg.D&E   $ MM% ]]6 "$==)=> }}%56mmG$ i( i( i(}}W% h'  I ^^N3 ( 1 1 ? ? |@\ ]nnW%nnW%  ? s3BHc  ddl}ddlm ddlm}ddlm d}tjt|jdtjt|jd tjt|jd tjt|jd |jd tjtjd tjitjdzt!|\ }}|j# d|j$d ffd }|j#|d|j$d f fd } |j#|d|j$d f fd } y#t$r}td|d}~wwxYw)zIAdd OAuth routes to the FastAPI app (login, callback handler and logout).rN)MismatchingStateError)OAuthRedirectResponseCannot initialize OAuth to due a missing library. Please run `pip install huggingface_hub[oauth]` or add `huggingface_hub[oauth]` to your requirements.txt file.zOAuth is required but '{}' environment variable is not set. Make sure you've enabled OAuth in your Space by setting `hf_oauth: true` in the Space metadata.OAUTH_CLIENT_IDrE OAUTH_SCOPESOPENID_PROVIDER_URL huggingfacer5z!/.well-known/openid-configuration)r client_id client_secret client_kwargsserver_metadata_urlrUrVcnKt|}jj||d{S7w)z)Endpoint that redirects to HF OAuth page.N)_generate_redirect_urirrauthorize_redirect)rU redirect_urioauths r& oauth_loginz&_add_oauth_routes..oauth_login$s2.g6 &&99'<PPPPs +535cK jj|d{}tjd ||j d < t#|S79#$rt|jj dd}|jj d}d|dzi}|r||d< dt j j|}|tjkDrNtjj d}| tddd |jd z} ||zcYS |cYSwxYww) )Endpoint that handles the OAuth callback.N _nb_redirectsr _target_urlr ? SPACE_HOSTzoApp is not running in a Space (SPACE_HOST environment variable is not set). Cannot redirect to non-iframe view.https://r@z@Successfully logged in with OAuth. Storing user info in session.rX)rrauthorize_access_tokenint query_paramsrburllibparse urlencoder OAUTH_MAX_REDIRECTSrLenviron RuntimeErrorrstriprNrar`_get_redirect_target) rUrX nb_redirects target_urlrrzhosthost_urlrjrm login_urir{s r&oauth_redirect_callbackz2_add_oauth_routes..oauth_redirect_callback*sI 2$00GGPPJ:  WX(2 % 4W =>>?Q$ 2w3377KLL --11-@J9HXYIY7ZL.8 ]+'[&,,*@*@*N)OPL i;;;zz~~l3<&J & C(88'<(?@@$L1 13 2sDEAAA5EACE5E7E?EEEcKtjd|jjddt |Sw)zGEndpoint that logs out the user (e.g. delete info from cookie session).z7Logged out with OAuth. Removing user info from session.rXN)rNrar`popr)rUrms r& oauth_logoutz'_add_oauth_routes..oauth_logoutOs;  NOL$/ 4W =>>sAA)fastapi'authlib.integrations.base_client.errorsrj%authlib.integrations.starlette_clientrkfastapi.responsesrmrDr ro ValueErrorformatrErprqregister_get_oauth_urisrbRequest)r7r8rrkrRmsg callback_uri logout_urir|rrrjrmrr{s @@@@r&rPrPs Q?6 ;  ($5677$$,$9:;;%N344$$,$9:;; GE NN ++33 6 67%99<__ +:,*G'I|Z WWYQ7??Q7GQQ  WW\"?w"?CS"?"?H WWZ?GOO?8H??[  F  sF++ G4 GGc ddl}ddlm ddlm t jdt t|\} }|j|d|jd f fd }|j d|jd f fd }|j|d|jd f fd }y#t $r}t d|d}~wwxYw) zAdd fake oauth routes if app is run locally and OAuth is enabled. Using OAuth will have the same behavior as in a Space but instead of authenticating with HF, a mocked user profile is added to the session. rNrl)URLrnzOAuth is not supported outside of a Space environment. To help you debug your app locally, the oauth endpoints are mocked to return your profile and token. To make it work, your machine must be logged in to Huggingface.rUrVc|Kt|}dztjjd|izSw)z.Fake endpoint that redirects to HF OAuth page.rr)rxrrr)rUrzrmrs r&r|z-_add_mocked_oauth_routes..oauth_loginps=.g6  s 2V\\5K5K]\hLi5j jkks9<cLK|jd<t|Sw)r~rX)r`r)rUrmmocked_oauth_infos r&rz9_add_mocked_oauth_routes..oauth_redirect_callbackws(): % 4W =>>s!$cK|jjdddjdi|j}|dSw)z=Endpoint that logs out the user (e.g. delete cookie session).rXNr@i.)url status_coder$)r`rinclude_query_paramsr)rU logout_urlrmrs r&rz._add_mocked_oauth_routes..oauth_logout}sI L$/2SX22JW5I5IJ JC@@sA A ) rrrmstarlette.datastructuresrrDwarningswarn_get_mocked_oauth_inforrbr) r7r8rrRrrr|rrrmrrrs @@@@r&rQrQWs 60 MM x/0*9,*G'I|Z WWYl7??l7Gll  WW\?w?CS??  WWZAGOOA8HAA;  F  sC C CCcLd|jvr|jd}n,dtjj|jz}|j dj |}t |}|jjdr|jdd}|S)Nrz/?r)rz .hf.spacezhttp://r) rrrrurl_forrr!netlocendswithreplace)rUtargetrzredirect_uri_as_strs r&rxrxs,,,%%m4 ..w/C/CDD??#<=RR_eRfLl+##K0199)ZP r%default_targetc:|jjd|S)Nr)rrb)rUrs r&rrs    # #M> BBr%ct}| tdt}|ddk7r td|ddddd tt jdzd |d |d d |d |ddddddddd dS)NaYour machine must be logged in to HF to debug an OAuth app locally. Please run `hf auth login` or set `HF_TOKEN` as environment variable with one of your access token. You can generate a new token in your settings page (https://huggingface.co/settings/tokens).typeuserzYour machine is not logged in with a personal account. Please use a personal access token. You can generate a new token in your settings page (https://huggingface.co/settings/tokens).beareripFOOBARzopenid profilehf_oauth__refresh_token 0123456789fullnamerzhttps://huggingface.co/ avatarUrlr;z$00000000-0000-0000-0000-000000000000i daaaaaaaaaaaaaaaaaaaidzhttps://huggingface.co) rrrr+rr,aud auth_timenonceiatexpiss)r1 token_type expires_inid_tokenr5 refresh_tokenr_rY)rrr rtime)tokenrs r&rrs KE } F   8D F|v 9  !!2$))+&4$"&v,0f?K(9#*+   r%cN|jd}|rd|}|d|d|dfS)Nr@z/oauth/huggingface/loginz/oauth/huggingface/callbackz/oauth/huggingface/logout)rKrBs r&rrsL%%c*L<.) .01 .34 .12 r%)r@))r6rGloggingrLr urllib.parserr dataclassesrtypingrrrrrr r r;r hf_apir utilsrr getLoggerrrNrrr(r0r!rTrhrPrQrxrrrr$r%r&rs{ !MMM*   8 $ ^^ ^B '''' ''T  0?A"3?A3?A?AD:%6:8I;N:zX?,X?CX?DX?v+A"3+A3+AQU+A\ $5 #  C"3CSCSVC((V#c3m0Dr%