From e3720181f8b2675ce230ceeeb0cdf02708a8e54a Mon Sep 17 00:00:00 2001 From: Guillaume Dorce Date: Fri, 9 Sep 2022 14:18:46 +0200 Subject: [PATCH] check auth and redirect to login or home --- client/src/App.tsx | 2 +- client/src/controllers/Auth.ts | 13 +++++++++++++ client/src/routes/home.tsx | 9 +++------ client/src/routes/login.tsx | 5 ++++- 4 files changed, 21 insertions(+), 8 deletions(-) create mode 100644 client/src/controllers/Auth.ts diff --git a/client/src/App.tsx b/client/src/App.tsx index 0106a54..f24698d 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -1,4 +1,4 @@ -import { BrowserRouter, Navigate, Outlet, Route, Routes } from 'react-router-dom'; +import { BrowserRouter, useNavigate, Outlet, Route, Routes } from 'react-router-dom'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import Login from './routes/login'; import Home from './routes/home'; diff --git a/client/src/controllers/Auth.ts b/client/src/controllers/Auth.ts new file mode 100644 index 0000000..0bfea26 --- /dev/null +++ b/client/src/controllers/Auth.ts @@ -0,0 +1,13 @@ +import { useCookies } from "react-cookie"; +import { useNavigate } from "react-router-dom"; + +const checkAuth = () => { + const [cookie, setCookie] = useCookies(['token']); + + if (cookie.token && cookie.token !== '') { + return true; + } + return false; +}; + +export { checkAuth }; \ No newline at end of file diff --git a/client/src/routes/home.tsx b/client/src/routes/home.tsx index 8586d4e..673e602 100644 --- a/client/src/routes/home.tsx +++ b/client/src/routes/home.tsx @@ -1,14 +1,11 @@ -import { useCookies } from "react-cookie"; -import { Navigate } from "react-router-dom"; import AppHeader from "@components/AppHeader"; +import { Navigate } from "react-router-dom"; +import { checkAuth } from "../controllers/Auth"; const Home = () => { - const [cookie, setCookie] = useCookies(["token"]); - - if (!cookie.token) { + if (!checkAuth()) { return ; } - return ( <> diff --git a/client/src/routes/login.tsx b/client/src/routes/login.tsx index 80561f0..815081b 100644 --- a/client/src/routes/login.tsx +++ b/client/src/routes/login.tsx @@ -4,8 +4,12 @@ import { useQuery } from '@tanstack/react-query'; import { useState } from 'react'; import { useCookies } from 'react-cookie'; import type { Token } from '../types'; +import { checkAuth } from '../controllers/Auth'; const Login = () => { + if (checkAuth()) { + return ; + } const [cookie, setCookie] = useCookies(['token']); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); @@ -43,7 +47,6 @@ const Login = () => { return ( <> - {cookie.token && }
Groupomania