Untitled

 avatar
unknown
plain_text
a year ago
1.8 kB
2
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 = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  return username && password;
};

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

const PrivateRoute = ({ element, path }) => {
  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 !== '/') {
      localStorage.removeItem('isBackToLogin');
      return <Navigate to="/" />;
    }
  } 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={<
Leave a Comment