From 363936641a31b0b508197d41bea1ce116931b5d4 Mon Sep 17 00:00:00 2001
From: Paweł Bernaciak <pawelbernaciak@zohomail.eu>
Date: Sat, 20 Jan 2024 11:03:44 +0100
Subject: New element creator

---
 frontend/src/App.tsx | 29 +++++++++++++++++++++++------
 1 file changed, 23 insertions(+), 6 deletions(-)

(limited to 'frontend/src/App.tsx')

diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 7aae66c..49e6992 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,10 +1,13 @@
 import { CredentialResponse, GoogleLogin } from '@react-oauth/google';
-import { FC, useEffect, useState } from 'react';
+import { FC, useEffect } from 'react';
 import { LoginRequest, LoginResponse, User } from './types';
 import ElementList from './components/ElementList';
+import { userStore } from './stores';
+import toast from 'react-hot-toast';
 
 const App: FC = () => {
-  const [user, setUser] = useState<User | undefined>(undefined);
+  const user = userStore((store) => store.user);
+  const setUser = userStore((store) => store.setUser);
 
   useEffect(() => {
     const userString = localStorage.getItem('user');
@@ -12,8 +15,21 @@ const App: FC = () => {
       return;
     }
 
-    setUser(JSON.parse(userString));
-  }, []);
+    const userObject = JSON.parse(userString) as User;
+    fetch(`/api/user/${userObject.id}`).then((resp) => {
+      if (resp.status == 401) {
+        toast.error(
+          'Your authorization has expired. You have to log in again.',
+        );
+        localStorage.removeItem('user');
+      } else if (resp.status == 404) {
+        toast.error("Your account doesn't exist anymore.");
+        localStorage.removeItem('user');
+      } else {
+        setUser(JSON.parse(userString));
+      }
+    });
+  }, [setUser]);
 
   const login = async (credentials: CredentialResponse) => {
     if (credentials.credential == null) {
@@ -25,6 +41,7 @@ const App: FC = () => {
     const loginRequest: LoginRequest = {
       googleToken: credentials.credential,
     };
+
     const loginResponse = await fetch('/api/auth/login', {
       method: 'POST',
       credentials: 'include',
@@ -48,8 +65,8 @@ const App: FC = () => {
       console.log('Error connecting to API. Code: ', userInfoResponse.status);
       return;
     }
-    const userResponse: User = await userInfoResponse.json();
 
+    const userResponse: User = await userInfoResponse.json();
     localStorage.setItem('user', JSON.stringify(userResponse));
     setUser(userResponse);
   };
@@ -89,6 +106,6 @@ const App: FC = () => {
       <ElementList />
     </div>
   );
-}
+};
 
 export default App;
-- 
cgit v1.2.3

