From fc942db1a10f13df63be7f3986314f15cd005ed6 Mon Sep 17 00:00:00 2001 From: grimhilt Date: Sat, 5 Aug 2023 21:30:29 +0200 Subject: [PATCH] logged in required --- src/components/app-router.jsx | 9 +++++---- src/pages/auth.jsx | 11 +++++++++-- src/tools/grant-access.jsx | 15 +++++++++++++++ 3 files changed, 29 insertions(+), 6 deletions(-) diff --git a/src/components/app-router.jsx b/src/components/app-router.jsx index 2f90437..515e13c 100644 --- a/src/components/app-router.jsx +++ b/src/components/app-router.jsx @@ -6,15 +6,16 @@ import Playlists from '../pages/playlists'; import Playlist from '../pages/playlist'; import Files from '../pages/files'; import Authentication from '../pages/auth'; +import { LoginRequired } from '../tools/grant-access'; const AppRouter = () => { return ( } /> - } /> - } /> - } /> - } /> + } />} /> + } />} /> + } />} /> + } />} /> } /> } /> diff --git a/src/pages/auth.jsx b/src/pages/auth.jsx index 5887701..d7b0d01 100644 --- a/src/pages/auth.jsx +++ b/src/pages/auth.jsx @@ -6,10 +6,11 @@ import { useEffect, useState } from 'react'; import setNotification from './errors/error-notification'; import API from '../services/api'; -const Authentication = () => { +const Authentication = ({ redirect }) => { const { user, setUser } = useAuth(); const navigate = useNavigate(); const [isLoading, setIsLoading] = useState(false); + const [loggedIn, setLoggedIn] = useState(false); useEffect(() => { if (user) navigate('/'); @@ -36,7 +37,11 @@ const Authentication = () => { if (res.status === 200) { setUser(res.data); localStorage.setItem('user', res.data); - navigate('/'); + if (redirect) { + setLoggedIn(true); + } else { + navigate('/'); + } } else { setNotification(true, res.message); setIsLoading(false); @@ -48,6 +53,8 @@ const Authentication = () => { }); }; + if (loggedIn) return redirect; + return ( { const { user } = useAuth(); return roles.includes(user) ? children : null; }; +export const LoginRequired = ({ children }) => { + const { user } = useAuth(); + if (!user) return <Authentication redirect={children} />; + else return children; +}; + export default GrantAccess;