File size: 2,384 Bytes
5ecbfe5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bb3a2b
 
5ecbfe5
 
 
 
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { oauthLoginUrl, oauthHandleRedirectIfPresent } from "@huggingface/hub";

interface OAuthResult {
  accessToken: string;
  userInfo?: {
    name?: string;
    email?: string;
    [key: string]: any;
  };
}

declare global {
  interface Window {
    huggingface: {
      variables: {
        OAUTH_SCOPES: string; // Changed from string[] to string
      };
    };
  }
}

async function initializeAuth(): Promise<void> {
  try {
    console.log("huggingface env", window.huggingface);

    let oauthResult: OAuthResult | null = null;
    const storedAuth = localStorage.getItem("oauth");

    if (storedAuth) {
      try {
        oauthResult = JSON.parse(storedAuth);
      } catch (error) {
        console.error("Failed to parse stored OAuth data:", error);
        localStorage.removeItem("oauth");
      }
    }

    const redirectResult = await oauthHandleRedirectIfPresent();
    if (redirectResult) {
      oauthResult = redirectResult as OAuthResult;
    }

    if (oauthResult) {
      const preElement = document.querySelector("pre");
      if (preElement) {
        preElement.textContent = JSON.stringify(oauthResult, null, 2);
      }

      localStorage.setItem("oauth", JSON.stringify(oauthResult));

      const signoutButton = document.getElementById("signout");
      if (signoutButton) {
        signoutButton.style.removeProperty("display");
        signoutButton.onclick = async () => {
          localStorage.removeItem("oauth");
          window.location.href = window.location.href.replace(/\?.*$/, "");
          window.location.reload();
        };
      }
    } else {
      const signinButton = document.getElementById("signin");
      if (signinButton) {
        signinButton.style.removeProperty("display");
        signinButton.onclick = async () => {
          try {
            const loginUrl = await oauthLoginUrl({
              scopes: window.huggingface.variables.OAUTH_SCOPES,
            });
            window.location.href = `${loginUrl}&prompt=consent`;
          } catch (error) {
            console.error("Failed to generate login URL:", error);
          }
        };
      }
    }
  } catch (error) {
    console.error("Authentication initialization failed:", error);
  }
}

// Initialize the authentication flow
initializeAuth().catch((error) => {
  console.error("Fatal error during authentication initialization:", error);
});