From d829fffc46318983ab1f2b38c2fc582fe883b379 Mon Sep 17 00:00:00 2001 From: ZihaoQian Date: Fri, 4 Oct 2024 23:17:04 -0400 Subject: [PATCH] Logout functionality After login, login button change to logout, make sure users won't login again. --- code/client/src/App.js | 39 +++++++++++++++++++++++++---- code/client/src/components/Login.js | 3 ++- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/code/client/src/App.js b/code/client/src/App.js index 93d99d75d..b9c64ab2d 100644 --- a/code/client/src/App.js +++ b/code/client/src/App.js @@ -6,7 +6,8 @@ import CreateUser from "./components/CreateUser.js"; import ViewUsers from "./components/ViewUsers.js"; import DailyData from "./components/DailyData.js"; import CreateGoal from "./components/CreateGoal.js"; - +import React, { useState, useEffect } from 'react'; +import LogoutIcon from '@mui/icons-material/Logout'; // Styling import { createTheme, @@ -48,7 +49,25 @@ const theme = createTheme({ }, }); + + function App() { + const [isAuthenticated, setIsAuthenticated] = useState(false); + + // On component mount, check if user is already logged in + useEffect(() => { + const token = localStorage.getItem('authToken'); + setIsAuthenticated(!!token); + }, []); + + const handleLogout = () => { + + localStorage.removeItem('authToken'); + + setIsAuthenticated(false); + + // navigate('/login'); + }; return ( @@ -111,16 +130,26 @@ function App() { + {!isAuthenticated ? ( - {" "} - {" "} + - + ) : ( + + + + + + + + + )} + @@ -173,7 +202,7 @@ function App() { } /> } /> } /> - } /> + } /> } /> } /> diff --git a/code/client/src/components/Login.js b/code/client/src/components/Login.js index 2d61694bb..6e0eab8f1 100644 --- a/code/client/src/components/Login.js +++ b/code/client/src/components/Login.js @@ -21,7 +21,7 @@ import { link, } from "./style/styles.js"; -function Login() { +function Login({ setIsAuthenticated }) { // status to store login status const [formData, setFormData] = useState({ email: "", @@ -56,6 +56,7 @@ function Login() { // store token localStorage.setItem("authToken", response.data.token); // redirect to home page + setIsAuthenticated(true); //console.log('login success:', response.data); navigate("/"); } catch (error) {