summaryrefslogtreecommitdiff
path: root/frontend/src/App.tsx
blob: 7aae66c7b62885c9e27da465fbf430b96d7ad03c (plain)
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
import { CredentialResponse, GoogleLogin } from '@react-oauth/google';
import { FC, useEffect, useState } from 'react';
import { LoginRequest, LoginResponse, User } from './types';
import ElementList from './components/ElementList';

const App: FC = () => {
  const [user, setUser] = useState<User | undefined>(undefined);

  useEffect(() => {
    const userString = localStorage.getItem('user');
    if (userString == null) {
      return;
    }

    setUser(JSON.parse(userString));
  }, []);

  const login = async (credentials: CredentialResponse) => {
    if (credentials.credential == null) {
      console.log('Error getting credentials from google');
      return;
    }

    // Authenticate with API and get user ID
    const loginRequest: LoginRequest = {
      googleToken: credentials.credential,
    };
    const loginResponse = await fetch('/api/auth/login', {
      method: 'POST',
      credentials: 'include',
      mode: 'cors',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(loginRequest),
    });
    if (!loginResponse.ok) {
      console.log('Error connecting to API. Code: ', loginResponse.status);
      return;
    }
    const userLoginResponse: LoginResponse = await loginResponse.json();

    //Get info about user using ID
    const userInfoResponse = await fetch(`/api/user/${userLoginResponse.id}`, {
      credentials: 'include',
    });
    if (!userInfoResponse.ok) {
      console.log('Error connecting to API. Code: ', userInfoResponse.status);
      return;
    }
    const userResponse: User = await userInfoResponse.json();

    localStorage.setItem('user', JSON.stringify(userResponse));
    setUser(userResponse);
  };

  const logout = async (e: React.MouseEvent<HTMLAnchorElement, MouseEvent>) => {
    e.preventDefault();

    const response = await fetch('api/auth/logout', {
      method: 'POST',
      credentials: 'include',
    });
    if (response.status != 200) {
      console.log('Error logging out. Code: ', response.status);
      return;
    }

    localStorage.removeItem('user');
    setUser(undefined);
  };

  return (
    <div className="flex flex-col">
      <div className="flex flex-row space-x-2 px-3 my-2 justify-end">
        {user ? (
          <>
            <p>Hello {user.name}</p>
            <a
              className="cursor-pointer text-blue-500 underline"
              onClick={logout}>
              Logout
            </a>
          </>
        ) : (
          <GoogleLogin onSuccess={login} />
        )}
      </div>
      <ElementList />
    </div>
  );
}

export default App;