File size: 1,979 Bytes
f48f76d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d67e1c
 
 
 
 
 
 
 
f48f76d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
'use client';

import { useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useAuth } from '@/contexts/AuthContext';
import Loading from '@/components/Loading';

export default function HFOAuthCallbackPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { exchangeCodeForToken, error } = useAuth();
  const [localError, setLocalError] = useState<string | null>(null);

  useEffect(() => {
    const code = searchParams.get('code');
    const state = searchParams.get('state');
    const errorParam = searchParams.get('error');

    const handleAuth = async () => {
      if (errorParam) {
        setLocalError(errorParam);
        router.replace('/settings');
        return;
      }

      if (code && state) {
        const storedState = sessionStorage.getItem('HF_OAUTH_STATE');
        if (!storedState || storedState !== state) {
          setLocalError('Invalid or expired OAuth state. Please try signing in again.');
          sessionStorage.removeItem('HF_OAUTH_STATE');
          router.replace('/settings');
          return;
        }

        const success = await exchangeCodeForToken(code, state);
        if (success) {
          router.replace('/dashboard');
        } else {
          setLocalError('Authentication failed. Please try again.');
          router.replace('/settings');
        }
      } else {
        setLocalError('Invalid authentication callback.');
        router.replace('/settings');
      }
    };

    handleAuth();
  }, [exchangeCodeForToken, router, searchParams]);

  return (
    <div className="min-h-screen flex flex-col items-center justify-center text-gray-200 bg-gray-950 gap-4">
      <Loading />
      <p className="text-lg">Authenticating with Hugging Face…</p>
      {(localError || error) && (
        <p className="text-sm text-red-400 max-w-md text-center">
          {localError || error}
        </p>
      )}
    </div>
  );
}