Untitled
// index.jsx (or wherever you have your main app rendering logic) import React, { useEffect } from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; import './index.css'; import Login from './Login.jsx'; import WeatherApp from './Weatherdata.jsx'; import Dashboard from './Dashboard.jsx'; import { BrowserRouter, Routes, Route, Navigate, useNavigate } from 'react-router-dom'; import ImageFetcher from './FetchImage.jsx'; const isAuthenticated = () => { // Check if the user is authenticated, you can modify this based on your authentication logic const username = localStorage.getItem('name'); const password = localStorage.getItem('password'); return username && password; }; const isOnLoginPage = () => { return window.location.pathname === '/'; }; const PrivateRoute = ({ element, path }) => { const navigate = useNavigate(); const isBackToLogin = localStorage.getItem('isBackToLogin') === 'true'; useEffect(() => { const handlePopstate = () => { // Redirect to login when using the right arrow to navigate if (!isAuthenticated()) { navigate('/'); } }; window.addEventListener('popstate', handlePopstate); return () => { window.removeEventListener('popstate', handlePopstate); }; }, [navigate]); if (!isAuthenticated() && !isOnLoginPage()) { // If not authenticated and not on the login page, redirect to login if (!localStorage.getItem('isBackToLogin')) { // Set a flag to indicate reaching the login page through back button localStorage.setItem('isBackToLogin', 'true'); return <Navigate to="/" />; } // Clear authentication details when coming back to the login page localStorage.removeItem('name'); localStorage.removeItem('password'); // Prevent navigating forward without authentication if (isBackToLogin) { localStorage.removeItem('isBackToLogin'); navigate('/'); return null; } } else { // Clear the flag if authenticated or on the login page localStorage.removeItem('isBackToLogin'); } return ( <div onClick={() => (!isAuthenticated() && navigate('/')) || null}> {element} </div> ); }; const AppRouter = () => { return ( <React.StrictMode> <BrowserRouter> <Routes> <Route path="/" element={<Login />}></Route> <Route path="/Dashboard" element={<PrivateRoute element={<Dashboard />} path="/Dashboard" />} ></Route> <Route path="/Weatherdata" element={<PrivateRoute element={<WeatherApp />} path="/Weatherdata" />} ></Route> <Route path="/FetchImage" element={<PrivateRoute element={<ImageFetcher />} path="/FetchImage" />} ></Route> </Routes> </BrowserRouter> </React.StrictMode> ); }; ReactDOM.createRoot(document.getElementById('root')).render(<AppRouter />);
Leave a Comment