Spaces:
Running
Running
Download src/agent/oauth.js from VectorW/xlerobot-sim: direct link, hf CLI and curl.
- Browser
- Download file 2.35 kB
-
https://huggingface.co/spaces/VectorW/xlerobot-sim/resolve/main/src/agent/oauth.js
- Command line
-
hf download hf://spaces/VectorW/xlerobot-sim/src/agent/oauth.js
-
curl -L -o oauth.js https://huggingface.co/spaces/VectorW/xlerobot-sim/resolve/main/src/agent/oauth.js
2.35 kB
| // "Sign in with Hugging Face" for the agent's model calls. On a Space with hf_oauth enabled, the | |
| // static host provides the OAuth client in window.huggingface.variables and the token comes back by | |
| // redirect. Inside the Space page's iframe the sign-in runs in a new tab (HF's guidance for iframes); | |
| // the agent then works in that tab. | |
| import { oauthHandleRedirectIfPresent, oauthLoginUrl } from "@huggingface/hub"; | |
| const KEY = "xlerobot-sim.hf-oauth"; | |
| export function oauthAvailable() { | |
| return Boolean(globalThis.window?.huggingface?.variables?.OAUTH_CLIENT_ID); | |
| } | |
| const inIframe = () => { | |
| try { | |
| return window.self !== window.top; | |
| } catch { | |
| return true; | |
| } | |
| }; | |
| /** The stored or just-returned sign-in: {accessToken, name, expires} or null. */ | |
| export async function currentLogin() { | |
| try { | |
| const result = await oauthHandleRedirectIfPresent(); | |
| if (result) { | |
| const login = { accessToken: result.accessToken, name: result.userInfo?.preferred_username ?? result.userInfo?.name ?? "", expires: result.accessTokenExpiresAt?.toString?.() ?? null }; | |
| localStorage.setItem(KEY, JSON.stringify(login)); | |
| const url = new URL(location.href); | |
| for (const k of ["code", "state"]) url.searchParams.delete(k); | |
| history.replaceState(null, "", url); | |
| return login; | |
| } | |
| } catch (error) { | |
| console.warn("OAuth redirect:", error); | |
| } | |
| try { | |
| const login = JSON.parse(localStorage.getItem(KEY) ?? "null"); | |
| if (login && (!login.expires || new Date(login.expires) > new Date())) return login; | |
| } catch { | |
| // storage may be blocked | |
| } | |
| return null; | |
| } | |
| export async function signIn() { | |
| if (inIframe()) { | |
| // Open the app itself in a tab; it starts the redirect there. | |
| const url = new URL(location.href); | |
| url.searchParams.set("signin", "1"); | |
| window.open(url.toString(), "_blank", "noopener"); | |
| return; | |
| } | |
| const scopes = window.huggingface?.variables?.OAUTH_SCOPES ?? "openid profile inference-api"; | |
| window.location.href = (await oauthLoginUrl({ scopes })) + "&prompt=consent"; | |
| } | |
| export function signOut() { | |
| try { | |
| localStorage.removeItem(KEY); | |
| } catch { | |
| // ignore | |
| } | |
| } | |
| /** True when the page was opened to sign in (from the iframe's button). */ | |
| export function signInRequested() { | |
| return new URL(location.href).searchParams.get("signin") === "1"; | |
| } | |