Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
2.8 kB
1
Indexable
Never
// 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 = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  return username && password;
};

const isOnLoginPage = () => {
  return window.location.pathname === '/';
};

const PrivateRoute = ({ element, path }) => {
  const isBackToLogin = localStorage.getItem('isBackToLogin') === 'true';
  const hasVisitedLogin = localStorage.getItem('hasVisitedLogin') === 'true';

  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 the flag if trying to navigate to a protected route without logging in
    if (localStorage.getItem('isBackToLogin') && path !== '/') {
      // Perform authentication when coming back to the login page
      if (hasVisitedLogin) {
        // Redirect to login if authentication fails
        localStorage.removeItem('isBackToLogin');
        return <Navigate to="/" />;
      } else {
        // Set a flag indicating that the user has visited the login page
        localStorage.setItem('hasVisitedLogin', 'true');
      }
    }
  } else {
    // Clear the flag if authenticated or on the login page
    localStorage.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 />);
Leave a Comment