Yvonne Priscilla
update upload page
250ae22
// hooks/useAuth.ts
import { authFetch } from "@/lib/api";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { usePathname, useRouter } from "next/navigation";
interface MeResponse {
user_id: string;
username: string;
email: string;
full_name: string;
role: string;
is_active: boolean;
tenant_id: string;
created_at: string;
}
export const useAuth = () => {
const queryClient = useQueryClient();
const router = useRouter();
const pathname = usePathname();
// Get current user
const {
data: user,
isLoading: isLoadingUser,
error: userError,
} = useQuery<MeResponse>({
queryKey: ["me"],
queryFn: async () => {
const res = await authFetch("/api/auth/me");
if (!res.ok) throw new Error("Failed to fetch user");
return res.json();
},
staleTime: 1000 * 60 * 5,
retry: false,
enabled: pathname !== "/login",
});
// Logout mutation
const logoutMutation = useMutation({
mutationFn: async () => {
const res = await fetch("/api/auth/logout", {
method: "POST",
});
if (!res.ok) throw new Error("Logout failed");
return res.json();
},
onSuccess: () => {
queryClient.clear();
router.push("/login");
router.refresh();
},
});
return {
user,
isLoadingUser,
userError,
logout: logoutMutation.mutate,
isLoggingOut: logoutMutation.isPending,
isAuthenticated: !!user,
};
};