import { oauthLoginUrl, oauthHandleRedirectIfPresent } from "@huggingface/hub"; export interface HuggingFaceWindow extends Window { huggingface?: { variables: { OAUTH_SCOPES: string; }; }; } declare const window: HuggingFaceWindow; export type OAuthResult = Record | null | false; export class OAuthManager { private oauthResult: OAuthResult = null; constructor() { const storedOAuth = localStorage.getItem("oauth"); if (storedOAuth) { try { this.oauthResult = JSON.parse(storedOAuth); } catch { this.oauthResult = null; } } } async handleRedirect(): Promise { this.oauthResult ||= await oauthHandleRedirectIfPresent(); if (this.oauthResult !== null && this.oauthResult !== false) { localStorage.setItem("oauth", JSON.stringify(this.oauthResult)); } return this.oauthResult; } async initiateLogin(): Promise { const loginUrl = await oauthLoginUrl({ scopes: window.huggingface?.variables?.OAUTH_SCOPES ?? "", }); window.location.href = `${loginUrl}&prompt=consent`; } logout(): void { localStorage.removeItem("oauth"); window.location.href = window.location.href.replace(/\?.*$/, ""); window.location.reload(); } getAccessToken(): string | null { if (this.oauthResult && typeof this.oauthResult === "object") { return this.oauthResult.accessToken ?? null; } return null; } isAuthenticated(): boolean { return this.oauthResult !== null && this.oauthResult !== false; } } export const oauthManager = new OAuthManager();