Untitled
unknown
plain_text
a year ago
2.8 kB
4
Indexable
// index.jsx (or wherever you have your main app rendering logic) import React 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 } 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 = sessionStorage.getItem('name'); const password = sessionStorage.getItem('password'); return username && password; }; const isOnLoginPage = () => { return window.location.pathname === '/'; }; const PrivateRoute = ({ element, path }) => { const isBackToLogin = sessionStorage.getItem('isBackToLogin') === 'true'; const hasVisitedLogin = sessionStorage.getItem('hasVisitedLogin') === 'true'; if (!isAuthenticated() && !isOnLoginPage()) { // If not authenticated and not on the login page, redirect to login if (!sessionStorage.getItem('isBackToLogin')) { // Set a flag to indicate reaching the login page through back button sessionStorage.setItem('isBackToLogin', 'true'); return <Navigate to="/" />; } // Clear the flag if trying to navigate to a protected route without logging in if (sessionStorage.getItem('isBackToLogin') && path !== '/') { // Perform authentication when coming back to the login page if (hasVisitedLogin) { // Redirect to login if authentication fails sessionStorage.removeItem('isBackToLogin'); return <Navigate to="/" />; } else { // Set a flag indicating that the user has visited the login page sessionStorage.setItem('hasVisitedLogin', 'true'); } } } else { // Clear the flag if authenticated or on the login page sessionStorage.removeItem('isBackToLogin'); } return element; }; 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 />);
Editor is loading...
Leave a Comment