app.tsx

import { useState, useEffect } from 'react';
import Login from './Login/Login';
import { Toaster } from 'sonner';
import { HashRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { apiService } from './Services/apiService';
import ShimPages from './Pages/ShimManagement/ShimPages';
import UserManagementPages from './Pages/UserManagement/UserManagementPages';
import SettingsPages from './Pages/Settings/SettingsPages';
import ApiDocumentation from './Pages/ApiDocumentation/ApiDocumentation';

interface User {
  username: string;
  email: string;
  role: string;
  loginTime: Date;
  user_id: string;
}

export default function App() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const [isInitializing, setIsInitializing] = useState(true);

  // Check for existing authentication on app load
  useEffect(() => {
    const savedUser = localStorage.getItem('currentUser');
    const savedToken = localStorage.getItem('auth_token');
    const savedUserId = localStorage.getItem('user_id');
   
    if (savedUser) {
      try {
        const user = JSON.parse(savedUser);
        setCurrentUser(user);
        setIsAuthenticated(true);
       
        // Restore auth token to apiService
        if (savedToken) {
          apiService.setAuthToken(savedToken);
          console.log('✅ Auth token restored from localStorage');
        }
       
        // Log user_id status
        if (savedUserId) {
          console.log('✅ User ID available:', savedUserId);
        } else {
          console.warn('⚠️ User ID not found in localStorage');
        }
      } catch (error) {
        console.error('Error parsing saved user:', error);
        localStorage.removeItem('currentUser');
        localStorage.removeItem('auth_token');
        localStorage.removeItem('user_id');
      }
    }
    setIsInitializing(false);
  }, []);

  const handleLogin = (user: User) => {
    console.log("User logged in:", user);
    setIsAuthenticated(true);
    setCurrentUser(user);
    // Store user info in localStorage for persistence
    localStorage.setItem('currentUser', JSON.stringify(user));
    localStorage.setItem('user_id', user.user_id);
    // Navigate to dashboard on successful login
    window.location.hash = '/dashboard';
  };

  const handleLogout = () => {
    setIsAuthenticated(false);
    setCurrentUser(null);
    localStorage.removeItem('currentUser');
    localStorage.removeItem('auth_token');
    localStorage.removeItem('csrf_token');
    localStorage.removeItem('user_id');
    apiService.setAuthToken(null);
    apiService.setCSRFToken(null);
    console.log('✅ Logged out and cleared all tokens and user_id');
  };

  // Component to protect routes that require authentication
  const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
    if (!isAuthenticated) {
      return <Navigate to="/login" replace />;
    }
    return <>{children}</>;
  };

  // Component to protect admin-only routes
  const AdminRoute = ({ children }: { children: React.ReactNode }) => {
    if (!isAuthenticated) {
      return <Navigate to="/login" replace />;
    }
    if (currentUser?.role?.toLowerCase() !== 'admin') {
      return <Navigate to="/home" replace />;
    }
    return <>{children}</>;
  };

  if (isInitializing) {
    return (
      <div className="min-h-screen bg-white flex items-center justify-center">
        <div className="text-center">
          <div className="w-16 h-16 bg-[#00052e] rounded-lg flex items-center justify-center mx-auto mb-4">
            <span className="text-white font-bold text-lg">FORD</span>
          </div>
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#00052e] mx-auto"></div>
          <p className="text-gray-600 mt-2">Loading...</p>
        </div>
      </div>
    );
  }

  return (
    <Router>
      <div className="min-h-screen bg-white">
        <Routes>
          {/* Shim Management Dashboard - PROTECTED (Login required) */}
          <Route
            path="/dashboard"
            element={
              <ProtectedRoute>
                <ShimPages onLogout={handleLogout} currentUser={currentUser} />
              </ProtectedRoute>
            }
          />

          <Route
            path="/shim-dashboard"
            element={
              <ProtectedRoute>
                <ShimPages onLogout={handleLogout} currentUser={currentUser} />
              </ProtectedRoute>
            }
          />

          {/* All Assembly and Tooling routes removed - no longer needed */}

          {/* Admin Settings Route - Admin only */}
          <Route
            path="/admin-settings"
            element={
              <AdminRoute>
                <UserManagementPages onLogout={handleLogout} currentUser={currentUser} />
              </AdminRoute>
            }
          />

          {/* User Management Route - Requires authentication */}
          <Route
            path="/users"
            element={
              <ProtectedRoute>
                <UserManagementPages onLogout={handleLogout} currentUser={currentUser} />
              </ProtectedRoute>
            }
          />

          {/* Profile Settings Route - Requires authentication */}
          <Route
            path="/profile-settings"
            element={
              <ProtectedRoute>
                <UserManagementPages onLogout={handleLogout} currentUser={currentUser} />
              </ProtectedRoute>
            }
          />

          {/* Settings Route - Requires authentication */}
          <Route
            path="/settings"
            element={
              <ProtectedRoute>
                <SettingsPages currentUser={currentUser} onLogout={handleLogout} />
              </ProtectedRoute>
            }
          />

          {/* API Documentation - PROTECTED */}
          <Route
            path="/api-docs"
            element={
              <ProtectedRoute>
                <ApiDocumentation />
              </ProtectedRoute>
            }
          />

          {/* Shim Log - PROTECTED (Login required) */}
          <Route
            path="/shim-log"
            element={
              <ProtectedRoute>
                <ShimPages onLogout={handleLogout} currentUser={currentUser} />
              </ProtectedRoute>
            }
          />

          {/* Shim Entry - PROTECTED (Login required) */}
          <Route
            path="/shim-entry"
            element={
              <ProtectedRoute>
                <ShimPages onLogout={handleLogout} currentUser={currentUser} />
              </ProtectedRoute>
            }
          />


          {/* Login Route - Redirect to dashboard if already authenticated */}
          <Route
            path="/login"
            element={
              isAuthenticated ? <Navigate to="/dashboard" replace /> : <Login onLogin={handleLogin} />
            }
          />

          {/* Main Route - Redirect to login if not authenticated, dashboard if authenticated */}
          <Route
            path="/"
            element={
              isAuthenticated ? <Navigate to="/dashboard" replace /> : <Navigate to="/login" replace />
            }
          />

          {/* Catch all route - redirect to login if not authenticated */}
          <Route
            path="/*"
            element={
              isAuthenticated ? <Navigate to="/dashboard" replace /> : <Navigate to="/login" replace />
            }
          />
        </Routes>

        <Toaster
          position="top-right"
          toastOptions={{
            duration: 3000,
            style: {
              fontFamily: 'inherit',
            },
          }}
        />
      </div>
    </Router>
  );
}

Comments

Popular posts from this blog

Homesit

Login.js