File size: 4,204 Bytes
794cf6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import { writable, get } from "svelte/store";
import {
  oauthLoginUrl,
  oauthHandleRedirectIfPresent,
  type UserInfo,
} from "@huggingface/hub";

export interface AuthState {
  isAuthenticated: boolean;
  user: UserInfo | null;
  accessToken: string | null;
  expiresAt: number | null;
  loading: boolean;
  error: string | null;
}

function createAuthStore() {
  const { subscribe, set, update } = writable<AuthState>({
    isAuthenticated: false,
    user: null,
    accessToken: null,
    expiresAt: null,
    loading: true,
    error: null,
  });

  const getOAuthConfig = () => {
    const isProduction = window.location.hostname.includes("hf.space");
    const clientId = "87f5f1d1-6e9e-4962-98f0-e5f3831ec988";

    let redirectUrl: string;
    if (isProduction) {
      redirectUrl = `https://${window.location.hostname}/auth/callback`;
    } else {
      redirectUrl = `http://localhost:7860/auth/callback`;
    }

    return {
      clientId,
      redirectUrl,
      scopes: "openid profile inference-api",
    };
  };

  return {
    subscribe,

    async init() {
      update((state) => ({ ...state, loading: true }));

      try {
        const oauthResult = await oauthHandleRedirectIfPresent();

        if (oauthResult) {
          const { accessToken, accessTokenExpiresAt, userInfo } = oauthResult;

          set({
            isAuthenticated: true,
            user: userInfo,
            accessToken,
            expiresAt: accessTokenExpiresAt
              ? accessTokenExpiresAt.getTime()
              : null,
            loading: false,
            error: null,
          });

          sessionStorage.setItem(
            "hf_auth",
            JSON.stringify({
              accessToken,
              expiresAt: accessTokenExpiresAt
                ? accessTokenExpiresAt.getTime()
                : null,
              user: userInfo,
            }),
          );

          return true;
        }

        const stored = sessionStorage.getItem("hf_auth");
        if (stored) {
          const authData = JSON.parse(stored);

          if (!authData.expiresAt || authData.expiresAt > Date.now()) {
            set({
              isAuthenticated: true,
              user: authData.user,
              accessToken: authData.accessToken,
              expiresAt: authData.expiresAt,
              loading: false,
              error: null,
            });
            return true;
          } else {
            sessionStorage.removeItem("hf_auth");
          }
        }

        set({
          isAuthenticated: false,
          user: null,
          accessToken: null,
          expiresAt: null,
          loading: false,
          error: null,
        });

        return false;
      } catch (error) {
        console.error("Auth initialization error:", error);
        set({
          isAuthenticated: false,
          user: null,
          accessToken: null,
          expiresAt: null,
          loading: false,
          error:
            error instanceof Error ? error.message : "Authentication failed",
        });
        return false;
      }
    },

    async login() {
      const config = getOAuthConfig();

      try {
        const url = await oauthLoginUrl({
          clientId: config.clientId,
          redirectUrl: config.redirectUrl,
          scopes: config.scopes,
        });

        window.location.href = url;
      } catch (error) {
        console.error("Login error:", error);
        update((state) => ({
          ...state,
          error: error instanceof Error ? error.message : "Login failed",
        }));
      }
    },

    logout() {
      sessionStorage.removeItem("hf_auth");
      set({
        isAuthenticated: false,
        user: null,
        accessToken: null,
        expiresAt: null,
        loading: false,
        error: null,
      });
    },

    getToken(): string | null {
      const state = get({ subscribe });
      return state.accessToken;
    },

    isTokenValid(): boolean {
      const state = get({ subscribe });
      if (!state.accessToken) return false;
      if (!state.expiresAt) return true;
      return state.expiresAt > Date.now();
    },
  };
}

export const authStore = createAuthStore();