Files
Checkmate/client/src/components/auth-verifier/index.tsx
T

64 lines
1.9 KiB
TypeScript
Raw Normal View History

2025-11-13 13:47:26 -08:00
import { useAppDispatch } from "@/hooks/AppHooks";
import type { IUser } from "@/types/user";
import {
setAuthenticated,
setUser,
logout,
setSelectedTeamId,
} from "@/features/authSlice";
import { useEffect, useState } from "react";
import { useAppSelector } from "@/hooks/AppHooks";
import type { ReactNode } from "react";
2025-12-15 23:36:50 +00:00
import { useGetOnDemand } from "@/hooks/UseApi";
2025-11-24 22:50:33 +00:00
import { useLocation, useNavigate } from "react-router-dom";
2025-11-13 13:47:26 -08:00
export const AuthVerifier = ({ children }: { children: ReactNode }) => {
const location = useLocation();
2025-11-24 22:50:33 +00:00
const navigate = useNavigate();
2025-11-13 13:47:26 -08:00
const isAuthRoute =
["/login", "/register"].includes(location.pathname) ||
2025-11-21 23:44:20 +00:00
location.pathname.startsWith("/recovery") ||
location.pathname.startsWith("/register/");
2025-11-13 13:47:26 -08:00
const isPublicRoute = location.pathname.startsWith("/status-pages/public");
const [isVerifying, setIsVerifying] = useState(true);
const dispatch = useAppDispatch();
const selectedTeamId = useAppSelector((state) => state.auth.selectedTeamId);
2025-12-15 23:36:50 +00:00
const { get: getOnDemand } = useGetOnDemand<IUser>();
2025-11-13 13:47:26 -08:00
useEffect(() => {
if (isAuthRoute || isPublicRoute) {
setIsVerifying(false);
return;
}
const verify = async () => {
try {
2025-12-15 23:36:50 +00:00
const res = await getOnDemand("/me");
const user: IUser = res?.data as IUser;
2025-11-13 13:47:26 -08:00
dispatch(setAuthenticated(true));
dispatch(setUser(user));
2025-11-24 22:50:33 +00:00
if (user.teams.length === 0) {
navigate("/no-team");
return;
}
2025-11-13 13:47:26 -08:00
if (
!selectedTeamId ||
!user.teams.find((t) => t.id === selectedTeamId)
) {
dispatch(setSelectedTeamId(user.teams[0].id));
}
} catch (error) {
console.error(error);
dispatch(logout());
} finally {
setIsVerifying(false);
}
};
verify();
}, [dispatch]);
if (isVerifying) return null;
return <>{children}</>;
};