import { last } from "lodash-es"; import { ClientError } from "nice-grpc-web"; import { useEffect, useState } from "react"; import { toast } from "react-hot-toast"; import { useSearchParams } from "react-router-dom"; import Icon from "@/components/Icon"; import { authServiceClient } from "@/grpcweb"; import { absolutifyLink } from "@/helpers/utils"; import useNavigateTo from "@/hooks/useNavigateTo"; import { useUserStore } from "@/store/v1"; import { useTranslate } from "@/utils/i18n"; interface State { loading: boolean; errorMessage: string; } const AuthCallback = () => { const t = useTranslate(); const navigateTo = useNavigateTo(); const [searchParams] = useSearchParams(); const userStore = useUserStore(); const [state, setState] = useState({ loading: true, errorMessage: "", }); useEffect(() => { const code = searchParams.get("code"); const state = searchParams.get("state"); if (!code || !state) { setState({ loading: false, errorMessage: "Failed to authorize. Invalid state passed to the auth callback.", }); return; } const identityProviderId = Number(last(state.split("-"))); if (!identityProviderId) { setState({ loading: false, errorMessage: "No identity provider ID found in the state parameter.", }); return; } const redirectUri = absolutifyLink("/auth/callback"); (async () => { try { const { user } = await authServiceClient.signInWithSSO({ idpId: identityProviderId, code, redirectUri, }); setState({ loading: false, errorMessage: "", }); if (!user) { toast.error(t("message.login-failed")); return; } await userStore.fetchCurrentUser(); navigateTo("/"); } catch (error: any) { console.error(error); setState({ loading: false, errorMessage: (error as ClientError).details, }); } })(); }, [searchParams]); return (
{state.loading ? ( ) : (
{state.errorMessage}
)}
); }; export default AuthCallback;