Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

5.6 KB
Raw Blame
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useNavigate, useSearch } from "@tanstack/react-router";
import { jwtDecode } from "jwt-decode";

import { captureSignupCompleted } from "@app/components/analytics/experiments/signupFlow/signupExperiment";
import { AuthPageLayout } from "@app/components/auth/AuthPageLayout";
import { AuthPagePanel } from "@app/components/auth/AuthPagePanel";
import { createNotification } from "@app/components/notifications";
import { PageTitle } from "@app/components/PageTitle";
import SecurityClient from "@app/components/utilities/SecurityClient";
import Telemetry from "@app/components/utilities/telemetry/Telemetry";
import {
  Button,
  CardContent,
  useClientResendDelay,
  VerificationCodeForm,
  VerificationCodeHeader,
  VerificationCodeResend
} from "@app/components/v3";
import { ROUTE_PATHS } from "@app/const/routes";
import { isInfisicalCloud } from "@app/helpers/platform";
import { getHubSpotUtk } from "@app/helpers/utmTracking";
import { useSendEmailVerificationCode } from "@app/hooks/api";
import { useCompleteAccountSignup } from "@app/hooks/api/auth/queries";
import { fetchOrganizations } from "@app/hooks/api/organization/queries";

const CLIENT_RESEND_DELAY_SECONDS = 20;

export const SignupSsoPage = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const search = useSearch({ from: ROUTE_PATHS.Auth.SignUpSsoPage.id });
  const token = search.token as string;
  const callbackPort = search.callback_port;

  const [code, setCode] = useState("");

  const completeAccountSignup = useCompleteAccountSignup();

  const decoded = jwtDecode(token) as {
    email?: string;
    firstName?: string;
    lastName?: string;
    authMethod?: string;
    isEmailVerified?: boolean;
  };

  const { mutateAsync: sendEmailVerificationCode, isPending: isResending } =
    useSendEmailVerificationCode();
  const resendDelay = useClientResendDelay(CLIENT_RESEND_DELAY_SECONDS);

  useEffect(() => {
    SecurityClient.setSignupToken(token);
  }, [token]);

  const handleSubmit = async () => {
    const telemetry = new Telemetry().getInstance();

    const { token: accessToken } = await completeAccountSignup.mutateAsync({
      type: "alias",
      code,
      hubspotUtk: getHubSpotUtk()
    });

    SecurityClient.setSignupToken("");
    SecurityClient.setToken(accessToken);
    const { organizationId } = jwtDecode(accessToken) as { organizationId?: string };

    if (decoded.email) {
      const signupEmail = decoded.email.toLowerCase();
      telemetry.identify(signupEmail, signupEmail);
    }

    createNotification({
      text: "Successfully verified",
      type: "success"
    });

    // People who already belong to an org (SAML/OIDC/LDAP, invites) are joining an existing
    // workspace, so org setup doesn't apply; keep sending them straight in.
    const userOrgs = await fetchOrganizations();
    if (userOrgs.length > 0) {
      if (callbackPort) {
        navigate({
          to: "/login/select-organization",
          search: { org_id: organizationId, callback_port: callbackPort }
        });
      } else if (organizationId) {
        navigate({
          to: "/organizations/$orgId/projects",
          params: { orgId: organizationId }
        });
      } else {
        navigate({ to: "/login/select-organization" });
      }
      return;
    }

    if (isInfisicalCloud()) {
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({ event: "signup_completed" });
    }
    captureSignupCompleted("sso");

    navigate({ to: "/organizations/onboarding", search: { callback_port: callbackPort } });
  };

  const handleResendCode = async () => {
    try {
      await sendEmailVerificationCode(token);
      resendDelay.restartDelay();
      createNotification({
        text: "Successfully resent code",
        type: "success"
      });
    } catch {
      createNotification({
        text: "Failed to resend code",
        type: "error"
      });
    }
  };

  return (
    <AuthPageLayout
      headerAction={
        <Button asChild variant="outline" size="sm">
          <Link to="/login" search={{ callback_port: callbackPort }}>
            Log In
          </Link>
        </Button>
      }
    >
      <PageTitle title={t("signup.title")} />
      <link rel="icon" href="/infisical.ico" />
      <meta property="og:image" content="/images/message.png" />
      <meta property="og:title" content={t("signup.og-title") as string} />
      <meta name="og:description" content={t("signup.og-description") as string} />
      <div className="mx-auto flex w-full flex-col items-center justify-center">
        <AuthPagePanel>
          <VerificationCodeHeader
            title="We've sent a verification code to"
            recipient={decoded.email}
          />
          <CardContent>
            <VerificationCodeForm
              name="signup-sso-verification-code"
              value={code}
              onChange={setCode}
              onSubmit={handleSubmit}
              isPending={completeAccountSignup.isPending}
              error={
                completeAccountSignup.isError
                  ? "Oops. Your code is wrong. Please try again."
                  : undefined
              }
            >
              <VerificationCodeResend
                isDisabled={completeAccountSignup.isPending}
                isResending={isResending}
                remainingSeconds={resendDelay.remainingSeconds}
                onResend={handleResendCode}
              />
            </VerificationCodeForm>
          </CardContent>
        </AuthPagePanel>
      </div>
    </AuthPageLayout>
  );
};