Spaces:
Runtime error
Runtime error
import { oauthLoginUrl, oauthHandleRedirectIfPresent } from "@huggingface/hub"; | |
export interface HuggingFaceWindow extends Window { | |
huggingface?: { | |
variables: { | |
OAUTH_SCOPES: string; | |
}; | |
}; | |
} | |
declare const window: HuggingFaceWindow; | |
export type OAuthResult = Record<string, any> | 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<OAuthResult> { | |
this.oauthResult ||= await oauthHandleRedirectIfPresent(); | |
if (this.oauthResult !== null && this.oauthResult !== false) { | |
localStorage.setItem("oauth", JSON.stringify(this.oauthResult)); | |
} | |
return this.oauthResult; | |
} | |
async initiateLogin(): Promise<void> { | |
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(); | |