File size: 6,546 Bytes
970eef1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import { useState, useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { oauthLoginUrl, oauthHandleRedirectIfPresent } from "@huggingface/hub";
import { HF_CONFIG } from "../config/auth";

async function fetchUserInfo(token) {
  try {
    const response = await fetch("https://huggingface.co/api/whoami-v2", {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
    if (!response.ok) {
      throw new Error(`Failed to fetch user info: ${response.status}`);
    }
    return response.json();
  } catch (error) {
    console.error("Error fetching user info:", error);
    throw error;
  }
}

export function useAuth() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const location = useLocation();
  const navigate = useNavigate();

  // Initialisation de l'authentification
  useEffect(() => {
    let mounted = true;
    const initAuth = async () => {
      try {
        console.group("Auth Initialization");
        setLoading(true);

        // Vérifier s'il y a une redirection OAuth d'abord
        let oauthResult;
        try {
          oauthResult = await oauthHandleRedirectIfPresent();
          console.log("OAuth redirect handled successfully");
        } catch (oauthError) {
          console.error("OAuth redirect handling error:", oauthError);

          // If the error is invalid_grant, this might be a refresh token issue
          // The user might already be logged in, so let's check localStorage
          if (
            oauthError.message &&
            oauthError.message.includes("invalid_grant")
          ) {
            console.log(
              "Invalid grant error detected - checking local storage for existing auth"
            );
          } else {
            // For other errors, clear auth data
            localStorage.removeItem(HF_CONFIG.STORAGE_KEY);
            if (mounted) {
              setIsAuthenticated(false);
              setUser(null);
              setError(oauthError.message);
              setLoading(false);
            }
            console.groupEnd();
            return;
          }
        }

        // Si pas de redirection ou erreur invalid_grant, vérifier le localStorage
        if (!oauthResult) {
          const storedAuth = localStorage.getItem(HF_CONFIG.STORAGE_KEY);
          if (storedAuth) {
            try {
              const parsedAuth = JSON.parse(storedAuth);
              console.log("Found existing auth");

              // Vérifier si le token est valide en appelant l'API
              try {
                const userInfo = await fetchUserInfo(parsedAuth.access_token);
                if (mounted) {
                  setIsAuthenticated(true);
                  setUser({
                    username: userInfo.name,
                    token: parsedAuth.access_token,
                  });
                  console.log("Successfully authenticated from stored token");
                }
              } catch (tokenError) {
                console.error("Stored token validation failed:", tokenError);
                localStorage.removeItem(HF_CONFIG.STORAGE_KEY);
                if (mounted) {
                  setIsAuthenticated(false);
                  setUser(null);
                }
              }
            } catch (err) {
              console.log("Invalid stored auth data, clearing...", err);
              localStorage.removeItem(HF_CONFIG.STORAGE_KEY);
              if (mounted) {
                setIsAuthenticated(false);
                setUser(null);
              }
            }
          }
        } else {
          console.log("Processing OAuth redirect");
          const token = oauthResult.accessToken;
          const userInfo = await fetchUserInfo(token);

          const authData = {
            access_token: token,
            username: userInfo.name,
          };

          localStorage.setItem(HF_CONFIG.STORAGE_KEY, JSON.stringify(authData));

          if (mounted) {
            setIsAuthenticated(true);
            setUser({
              username: userInfo.name,
              token: token,
            });
          }

          // Rediriger vers la page d'origine
          const returnTo = localStorage.getItem("auth_return_to");
          if (returnTo) {
            navigate(returnTo);
            localStorage.removeItem("auth_return_to");
          }
        }
      } catch (err) {
        console.error("Auth initialization error:", err);
        if (mounted) {
          setError(err.message);
          setIsAuthenticated(false);
          setUser(null);
        }
      } finally {
        if (mounted) {
          setLoading(false);
        }
        console.groupEnd();
      }
    };

    initAuth();

    return () => {
      mounted = false;
    };
  }, [navigate, location.pathname]);

  const login = async () => {
    try {
      console.group("Login Process");
      setLoading(true);
      setError(null); // Clear any previous errors

      // Sauvegarder la route actuelle pour la redirection post-auth
      const currentRoute = window.location.hash.replace("#", "") || "/";
      localStorage.setItem("auth_return_to", currentRoute);

      // Déterminer l'URL de redirection en fonction de l'environnement
      const redirectUrl = HF_CONFIG.DEV_URL;
      console.log("Using redirect URL:", redirectUrl);

      // Générer l'URL de login et rediriger
      const loginUrl = await oauthLoginUrl({
        clientId: HF_CONFIG.CLIENT_ID,
        redirectUrl,
        scope: HF_CONFIG.SCOPE,
      });

      window.location.href = loginUrl + "&prompt=consent";

      console.groupEnd();
    } catch (err) {
      console.error("Login error:", err);
      setError(err.message);
      setLoading(false);
      console.groupEnd();
    }
  };

  const logout = () => {
    console.group("Logout Process");
    setLoading(true);
    try {
      console.log("Clearing auth data...");
      localStorage.removeItem(HF_CONFIG.STORAGE_KEY);
      localStorage.removeItem("auth_return_to");
      setIsAuthenticated(false);
      setUser(null);
      console.log("Logged out successfully");
    } catch (err) {
      console.error("Logout error:", err);
      setError(err.message);
    } finally {
      setLoading(false);
      console.groupEnd();
    }
  };

  return {
    isAuthenticated,
    user,
    loading,
    error,
    login,
    logout,
  };
}