File size: 1,476 Bytes
409830c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useState, useEffect } from 'react';
import Button from './Button';
import hf from '../../../assets/hf.svg';
import { oauthLoginUrl, oauthHandleRedirectIfPresent } from '@huggingface/hub';

const OAuthLogin = () => {
  const [isSignedIn, setIsSignedIn] = useState(false);

  useEffect(() => {
    const checkAuthStatus = async () => {
      let oauthResult = localStorage.getItem('oauth');
      if (oauthResult) {
        try {
          oauthResult = JSON.parse(oauthResult);
        } catch {
          oauthResult = null;
        }
      }

      if (!oauthResult) {
        oauthResult = await oauthHandleRedirectIfPresent();
        if (oauthResult) {
          localStorage.setItem('oauth', JSON.stringify(oauthResult));
        }
      }

      setIsSignedIn(!!oauthResult);
    };

    checkAuthStatus();
  }, []);

  const handleSignIn = async () => {
    let clientId = import.meta.env.VITE_OAUTH_CLIENT_ID;
    window.location.href = await oauthLoginUrl({ clientId });
  };

  const handleSignOut = () => {
    localStorage.removeItem('oauth');
    window.location.href = window.location.href.replace(/\?.*$/, '');
    setIsSignedIn(false);
  };

  return (
    <>
      {isSignedIn ? (
          <Button id="signout" imgUrl={hf} onClick={handleSignOut}>Sign out</Button>
      ) : (
        <Button id="signin" imgUrl={hf} onClick={handleSignIn}>
          Sign in with Hugging Face
        </Button>
      )}
      </>
  );
};

export default OAuthLogin;