File size: 1,624 Bytes
16c1c4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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();