auth WIP 2

This commit is contained in:
2025-08-28 18:37:26 +03:00
parent 533da219b3
commit d23546d6e0
9 changed files with 97 additions and 35 deletions

View File

@ -1,9 +1,16 @@
import { BrowserRouter as Router, Routes, Route, Navigate, Outlet, useLocation } from 'react-router-dom';
import {useContext } from "react";
import {useContext, useEffect, useState } from "react";
import AuthContext, { AuthProvider } from "./auth/auth-provider"
import ping from "./auth/ping";
import Login from "./pages/login/login"
import Register from "./pages/register/register"
import Home from "./pages/home/home"
import AuthContext, { AuthProvider } from "./auth/auth-provider"
import Dashboard from "./pages/dashboard/dashboard"
import Settings from "./pages/settings/settings"
import useAuth from './auth/auth';
function App() {
@ -16,7 +23,11 @@ function App() {
<Route element={<PrivateRoute />}>
<Route path='/' element={<Home />} />
<Route path='/dashboard' element={<Dashboard />} />
<Route path='/settings' element={<Settings />} />
</Route>
<Route path="*" element={<div>404</div>} />
</Routes>
</Router>
</AuthProvider>
@ -25,14 +36,34 @@ function App() {
const PrivateRoute = () => {
const { isAuthenticated } = useContext(AuthContext);
const { token } = useAuth();
const location = useLocation();
const [checked, setChecked] = useState(false);
const [isValid, setIsValid] = useState(false);
useEffect(() => {
const checkAuth = async () => {
if (!token) {
setIsValid(false);
setChecked(true);
return;
}
const result = await ping(token);
console.log(result)
setIsValid(result);
setChecked(true);
};
checkAuth();
}, [token]);
if (!checked) {
return <div>Checking server availability...</div>;
}
return (
isAuthenticated === true ?
<Outlet />
:
<Navigate to="/login" state={{ from: location }} replace />
isValid
? <Outlet />
: <Navigate to="/login" state={{ from: location }} replace />
);
}