Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.7 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, 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';

  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');
      return <Navigate to="/" />;
    }
  } else {
    // Clear the flag if authenticated or on the login page
    localStorage.removeItem('isBackToLogin');
  }

  const handleNavigate = () => {
    if (!isAuthenticated()) {
      // Redirect to login if not authenticated
      navigate('/');
    }
  };

  return <div onClick={handleNavigate}>{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