mirror of
https://github.com/freedbygrace/ActiveDirectoryManager.git
synced 2026-07-26 20:09:10 +00:00
Refactor authentication and routing logic for improved user experience and security.
Replit-Commit-Author: Agent Replit-Commit-Session-Id: 705f2157-ef97-4fbd-89e4-8c7f2ecaea90 Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/7ed01c5f-a82d-405a-b728-b2e3d127c60c/d48b8704-7beb-4365-80b8-d652bf12c6e7.jpg
This commit is contained in:
+3
-52
@@ -1,53 +1,4 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Switch, Route, useLocation } from "wouter";
|
||||
import { Toaster } from "@/components/ui/toaster";
|
||||
import NotFound from "@/pages/not-found";
|
||||
import AuthPage from "@/pages/auth-page";
|
||||
import DashboardPage from "@/pages/dashboard-page";
|
||||
import UsersPage from "@/pages/users-page";
|
||||
import GroupsPage from "@/pages/groups-page";
|
||||
import OUsPage from "@/pages/ous-page";
|
||||
import ComputersPage from "@/pages/computers-page";
|
||||
import DomainsPage from "@/pages/domains-page";
|
||||
import ApiTokensPage from "@/pages/api-tokens-page";
|
||||
import LdapConnectionsPage from "@/pages/ldap-connections-page";
|
||||
import LdapQueryBuilderPage from "@/pages/ldap-query-builder-page";
|
||||
import SettingsPage from "@/pages/settings-page";
|
||||
import UserManagementPage from "@/pages/user-management-page";
|
||||
import AuditLogsPage from "@/pages/audit-logs-page";
|
||||
import { ProtectedRoute } from "./lib/protected-route";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
function Router() {
|
||||
return (
|
||||
<Switch>
|
||||
<Route path="/auth">
|
||||
<AuthPage />
|
||||
</Route>
|
||||
<ProtectedRoute path="/" component={DashboardPage} />
|
||||
<ProtectedRoute path="/users" component={UsersPage} />
|
||||
<ProtectedRoute path="/groups" component={GroupsPage} />
|
||||
<ProtectedRoute path="/organizational-units" component={OUsPage} />
|
||||
<ProtectedRoute path="/computers" component={ComputersPage} />
|
||||
<ProtectedRoute path="/domains" component={DomainsPage} />
|
||||
<ProtectedRoute path="/api-tokens" component={ApiTokensPage} />
|
||||
<ProtectedRoute path="/ldap-connections" component={LdapConnectionsPage} />
|
||||
<ProtectedRoute path="/ldap-query-builder" component={LdapQueryBuilderPage} />
|
||||
<ProtectedRoute path="/audit-logs" component={AuditLogsPage} />
|
||||
<ProtectedRoute path="/settings" component={SettingsPage} />
|
||||
<ProtectedRoute path="/user-management" component={UserManagementPage} />
|
||||
<Route component={NotFound} />
|
||||
</Switch>
|
||||
);
|
||||
// This file is a placeholder - all the app logic is now in main.tsx
|
||||
export default function App() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<>
|
||||
<Router />
|
||||
<Toaster />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
import React, { useState, useContext } from "react";
|
||||
import { Link, useLocation } from "wouter";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
} from "lucide-react";
|
||||
import { useMobile } from "@/hooks/use-mobile";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { AuthContext } from "@/hooks/use-auth";
|
||||
import { ThemeToggle } from "@/components/theme-toggle";
|
||||
|
||||
type MenuItem = {
|
||||
@@ -46,14 +47,6 @@ type MenuSection = {
|
||||
items: MenuItem[];
|
||||
};
|
||||
|
||||
type UserType = {
|
||||
id: number;
|
||||
username: string;
|
||||
fullName?: string;
|
||||
email?: string;
|
||||
role?: string;
|
||||
};
|
||||
|
||||
const menuSections: MenuSection[] = [
|
||||
{
|
||||
title: "Active Directory",
|
||||
@@ -88,57 +81,20 @@ export function DashboardLayout({ children, title, description }: DashboardLayou
|
||||
const [location, navigate] = useLocation();
|
||||
const isMobile = useMobile();
|
||||
const [sidebarOpen, setSidebarOpen] = useState(!isMobile);
|
||||
const [user, setUser] = useState<UserType | null>(null);
|
||||
const auth = useContext(AuthContext);
|
||||
if (!auth) {
|
||||
console.error("Auth context not available");
|
||||
return <div>Authentication error. Please refresh the page.</div>;
|
||||
}
|
||||
const { user, logoutMutation } = auth;
|
||||
const { toast } = useToast();
|
||||
|
||||
// Fetch user data on component mount
|
||||
useEffect(() => {
|
||||
const fetchUserData = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/user', {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const userData = await response.json();
|
||||
setUser(userData);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching user data:', error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchUserData();
|
||||
}, []);
|
||||
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/logout', {
|
||||
method: 'POST',
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
toast({
|
||||
title: "Logged out",
|
||||
description: "You have been successfully logged out.",
|
||||
});
|
||||
logoutMutation.mutate(undefined, {
|
||||
onSuccess: () => {
|
||||
navigate('/auth');
|
||||
} else {
|
||||
toast({
|
||||
title: "Logout failed",
|
||||
description: "An error occurred during logout.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error during logout:', error);
|
||||
toast({
|
||||
title: "Logout failed",
|
||||
description: "An error occurred during logout.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Get user initials for avatar
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { Redirect, Route } from "wouter";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
export function ProtectedRoute({
|
||||
path,
|
||||
@@ -9,30 +9,10 @@ export function ProtectedRoute({
|
||||
path: string;
|
||||
component: () => React.JSX.Element;
|
||||
}) {
|
||||
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const checkAuth = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/user', {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
setIsAuthenticated(true);
|
||||
} else {
|
||||
setIsAuthenticated(false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error checking auth status:', error);
|
||||
setIsAuthenticated(false);
|
||||
}
|
||||
};
|
||||
|
||||
checkAuth();
|
||||
}, []);
|
||||
const { user, isLoading } = useAuth();
|
||||
|
||||
if (isAuthenticated === null) {
|
||||
// Show a loading indicator while authentication state is being determined
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Route path={path}>
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
@@ -42,7 +22,8 @@ export function ProtectedRoute({
|
||||
);
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
// Redirect to auth page if user is not authenticated
|
||||
if (!user) {
|
||||
return (
|
||||
<Route path={path}>
|
||||
<Redirect to="/auth" />
|
||||
@@ -50,6 +31,7 @@ export function ProtectedRoute({
|
||||
);
|
||||
}
|
||||
|
||||
// Render the component if the user is authenticated
|
||||
return (
|
||||
<Route path={path}>
|
||||
<Component />
|
||||
|
||||
+87
-11
@@ -1,17 +1,93 @@
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import App from "./App";
|
||||
import { Toaster } from "@/components/ui/toaster";
|
||||
import { Switch, Route, Redirect } from "wouter";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import NotFound from "@/pages/not-found";
|
||||
import AuthPage from "@/pages/auth-page";
|
||||
import DashboardPage from "@/pages/dashboard-page";
|
||||
import UsersPage from "@/pages/users-page";
|
||||
import GroupsPage from "@/pages/groups-page";
|
||||
import OUsPage from "@/pages/ous-page";
|
||||
import ComputersPage from "@/pages/computers-page";
|
||||
import DomainsPage from "@/pages/domains-page";
|
||||
import ApiTokensPage from "@/pages/api-tokens-page";
|
||||
import LdapConnectionsPage from "@/pages/ldap-connections-page";
|
||||
import LdapQueryBuilderPage from "@/pages/ldap-query-builder-page";
|
||||
import SettingsPage from "@/pages/settings-page";
|
||||
import UserManagementPage from "@/pages/user-management-page";
|
||||
import AuditLogsPage from "@/pages/audit-logs-page";
|
||||
import "./index.css";
|
||||
import { AuthProvider } from "./hooks/use-auth";
|
||||
import { AuthProvider, useAuth } from "./hooks/use-auth";
|
||||
import { ThemeProvider } from "./hooks/use-theme";
|
||||
import { queryClient } from "./lib/queryClient";
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ThemeProvider defaultTheme="system" storageKey="ad-management-theme">
|
||||
<AuthProvider>
|
||||
<App />
|
||||
</AuthProvider>
|
||||
</ThemeProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
// Create the App and use context appropriately
|
||||
function App() {
|
||||
return (
|
||||
<>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ThemeProvider defaultTheme="system" storageKey="ad-management-theme">
|
||||
<AuthProvider>
|
||||
<AppContent />
|
||||
</AuthProvider>
|
||||
</ThemeProvider>
|
||||
</QueryClientProvider>
|
||||
<Toaster />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// Protected route component that uses the useAuth hook
|
||||
function ProtectedRoute({
|
||||
path,
|
||||
component: Component
|
||||
}: {
|
||||
path: string;
|
||||
component: () => React.JSX.Element;
|
||||
}) {
|
||||
const { user } = useAuth();
|
||||
|
||||
return (
|
||||
<Route path={path}>
|
||||
{user ? <Component /> : <Redirect to="/auth" />}
|
||||
</Route>
|
||||
);
|
||||
}
|
||||
|
||||
// App content with routes that can safely use the useAuth hook
|
||||
function AppContent() {
|
||||
const { isLoading } = useAuth();
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Switch>
|
||||
<Route path="/auth">
|
||||
<AuthPage />
|
||||
</Route>
|
||||
<ProtectedRoute path="/" component={DashboardPage} />
|
||||
<ProtectedRoute path="/users" component={UsersPage} />
|
||||
<ProtectedRoute path="/groups" component={GroupsPage} />
|
||||
<ProtectedRoute path="/organizational-units" component={OUsPage} />
|
||||
<ProtectedRoute path="/computers" component={ComputersPage} />
|
||||
<ProtectedRoute path="/domains" component={DomainsPage} />
|
||||
<ProtectedRoute path="/api-tokens" component={ApiTokensPage} />
|
||||
<ProtectedRoute path="/ldap-connections" component={LdapConnectionsPage} />
|
||||
<ProtectedRoute path="/ldap-query-builder" component={LdapQueryBuilderPage} />
|
||||
<ProtectedRoute path="/audit-logs" component={AuditLogsPage} />
|
||||
<ProtectedRoute path="/settings" component={SettingsPage} />
|
||||
<ProtectedRoute path="/user-management" component={UserManagementPage} />
|
||||
<Route component={NotFound} />
|
||||
</Switch>
|
||||
);
|
||||
}
|
||||
|
||||
// Render the app
|
||||
createRoot(document.getElementById("root")!).render(<App />);
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect } from "react";
|
||||
import { useLocation } from "wouter";
|
||||
import { z } from "zod";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
@@ -24,7 +23,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { insertUserSchema } from "@shared/schema";
|
||||
import { apiRequest } from "@/lib/queryClient";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
|
||||
// Login form schema
|
||||
@@ -54,73 +53,19 @@ type RegisterFormValues = z.infer<typeof registerSchema>;
|
||||
export default function AuthPage() {
|
||||
const [location, navigate] = useLocation();
|
||||
const { toast } = useToast();
|
||||
const [isChecking, setIsChecking] = useState(true);
|
||||
|
||||
// Check if user is already logged in
|
||||
const { user, isLoading, loginMutation, registerMutation } = useAuth();
|
||||
|
||||
// Redirect if user is already logged in
|
||||
useEffect(() => {
|
||||
const checkAuth = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/user', {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
// User is already logged in, redirect to home
|
||||
navigate('/');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error checking auth status:', error);
|
||||
} finally {
|
||||
setIsChecking(false);
|
||||
}
|
||||
};
|
||||
|
||||
checkAuth();
|
||||
}, [navigate]);
|
||||
|
||||
// Login mutation
|
||||
const loginMutation = useMutation({
|
||||
mutationFn: async (credentials: LoginFormValues) => {
|
||||
const res = await apiRequest("POST", "/api/login", credentials);
|
||||
return await res.json();
|
||||
},
|
||||
onSuccess: (user) => {
|
||||
toast({
|
||||
title: "Login successful",
|
||||
description: `Welcome back, ${user.username}!`,
|
||||
});
|
||||
if (user) {
|
||||
navigate('/');
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast({
|
||||
title: "Login failed",
|
||||
description: error.message,
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
}, [user, navigate]);
|
||||
|
||||
// Register mutation
|
||||
const registerMutation = useMutation({
|
||||
mutationFn: async (credentials: any) => {
|
||||
const res = await apiRequest("POST", "/api/register", credentials);
|
||||
return await res.json();
|
||||
},
|
||||
onSuccess: (user) => {
|
||||
toast({
|
||||
title: "Registration successful",
|
||||
description: `Welcome, ${user.username}!`,
|
||||
});
|
||||
navigate('/');
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast({
|
||||
title: "Registration failed",
|
||||
description: error.message,
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
});
|
||||
// If still checking authentication status, show nothing
|
||||
if (isLoading) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Login form
|
||||
const loginForm = useForm<LoginFormValues>({
|
||||
|
||||
Reference in New Issue
Block a user