AeThex-OS/client/src/lib/auth.tsx
sirpiglr 3e9e10e757 Improve login flow and admin page access reliability
Refactor AuthProvider to await session refetch on login success and add a delay to admin page redirect to prevent immediate logout.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 279f1558-c0e3-40e4-8217-be7e9f4c6eca
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Event-Id: 12a0ed24-3282-4c06-bd03-d33c53459821
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/b984cb14-1d19-4944-922b-bc79e821ed35/279f1558-c0e3-40e4-8217-be7e9f4c6eca/nNnFCpK
Replit-Helium-Checkpoint-Created: true
2025-12-16 00:30:09 +00:00

90 lines
2.4 KiB
TypeScript

import { createContext, useContext, useState, useEffect, ReactNode } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
interface User {
id: string;
username: string;
isAdmin: boolean;
}
interface AuthContextType {
user: User | null;
isLoading: boolean;
isAuthenticated: boolean;
isAdmin: boolean;
login: (username: string, password: string) => Promise<void>;
logout: () => Promise<void>;
}
const AuthContext = createContext<AuthContextType | null>(null);
export function AuthProvider({ children }: { children: ReactNode }) {
const queryClient = useQueryClient();
const { data: session, isLoading } = useQuery({
queryKey: ["session"],
queryFn: async () => {
const res = await fetch("/api/auth/session", { credentials: "include" });
return res.json();
},
});
const loginMutation = useMutation({
mutationFn: async ({ username, password }: { username: string; password: string }) => {
const res = await fetch("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ username, password }),
});
if (!res.ok) {
const data = await res.json();
throw new Error(data.error || "Login failed");
}
return res.json();
},
onSuccess: async () => {
await queryClient.refetchQueries({ queryKey: ["session"] });
},
});
const logoutMutation = useMutation({
mutationFn: async () => {
await fetch("/api/auth/logout", { method: "POST", credentials: "include" });
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["session"] });
},
});
const login = async (username: string, password: string) => {
await loginMutation.mutateAsync({ username, password });
};
const logout = async () => {
await logoutMutation.mutateAsync();
};
const value: AuthContextType = {
user: session?.authenticated ? session.user : null,
isLoading,
isAuthenticated: !!session?.authenticated,
isAdmin: session?.user?.isAdmin || false,
login,
logout,
};
return (
<AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const context = useContext(AuthContext);
if (!context) {
throw new Error("useAuth must be used within an AuthProvider");
}
return context;
}