From e9ce5bfa292b6578ed1f448a539f08b0f71c30f7 Mon Sep 17 00:00:00 2001 From: Roman-hal <85693082+Roman-Hal@users.noreply.github.com> Date: Thu, 11 May 2023 20:17:59 +0100 Subject: [PATCH 1/2] Created_routing_login_logout Created routing for when the user is logged in or logged out. Safe routing --- client/src/App.js | 69 ++++++++++++++++++++++++--- client/src/Components/MainContent.js | 10 ++-- client/src/Components/ProfileIcone.js | 5 +- client/src/pages/History.js | 4 +- client/src/pages/LandingPage.js | 5 +- server/api.js | 14 ++++++ server/passport.js | 4 +- 7 files changed, 94 insertions(+), 17 deletions(-) diff --git a/client/src/App.js b/client/src/App.js index b3cbb21..cf8c4c8 100644 --- a/client/src/App.js +++ b/client/src/App.js @@ -1,4 +1,4 @@ -import { Route, Routes } from "react-router-dom"; +import { Route, Routes, Outlet, Navigate } from "react-router-dom"; import { useEffect, useState } from "react"; import About from "./pages/About"; @@ -10,13 +10,23 @@ import History from "./pages/History"; const App = () => { const [user, setUser] = useState(); + const [isAuthenticated, setIsAuthenticated] = useState(); + const [loading, setLoading] = useState(true); + + const PrivateWrapper = () => { + return isAuthenticated ? : ; + }; + + const LoginWrapper = () => { + return !isAuthenticated ? : ; + }; useEffect(() => { const fetchUser = async () => { try { const response = await fetch( - "http://localhost:3000/api/auth/login/success" ?? - "/api/auth/login/success", + "/api/auth/login/success" ?? + "http://localhost:3000/api/auth/login/success", { method: "GET", credentials: "include", @@ -40,13 +50,60 @@ const App = () => { fetchUser(); }, []); + //useEffect for checking authentication used to work! + /*useEffect(() => { + const getProfile = () => { + user ? setIsAuthenticated(true) : setIsAuthenticated(false); + setLoading(false); + }; + getProfile(); + }, [user]);*/ + + //!!SETTING authentication using fetch and backend! Keep here please for possible use!! + useEffect(() => { + const fetchProfile = async () => { + try { + const response = await fetch( + "/api/auth/login/profile" ?? + "http://localhost:3000/api/auth/login/profile", + { + method: "GET", + credentials: "include", + headers: { + Accept: "application/json", + "Content-type": "application/json", + "Access-Control-Allow-Credentials": true, + }, + } + ); + const json = await response.json(); + const result = json; + setIsAuthenticated(result); + setLoading(false); + } catch (error) { + //console.log("error", error); + return error; + } + }; + fetchProfile(); + }, []); + + if (loading) { + return
Loading...
; + } + + //wrappers for different safe and default routing return (
{/*
*/} - } /> - } /> - } /> + }> + } /> + + }> + } /> + } /> + } /> {/*