Skip to content

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

improvement: require otp from original email to change email

Scott Wilson1b968e74928f
diff --git a/backend/src/server/routes/v2/user-router.ts b/backend/src/server/routes/v2/user-router.ts
index 62810e5f30..62fba4a51e 100644
--- a/backend/src/server/routes/v2/user-router.ts
+++ b/backend/src/server/routes/v2/user-router.ts
@@ -141,6 +141,36 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "POST",
+ url: "/me/email-change/verify-current",
+ config: {
+ rateLimit: smtpRateLimit({
+ keyGenerator: (req) => req.permission.id
+ })
+ },
+ schema: {
+ operationId: "verifyCurrentEmailOtp",
+ body: z.object({
+ otpCode: z.string().trim().length(6)
+ }),
+ response: {
+ 200: z.object({
+ success: z.boolean(),
+ newEmail: z.string()
+ })
+ }
+ },
+ preHandler: verifyAuth([AuthMode.JWT], { requireOrg: false }),
+ handler: async (req) => {
+ const result = await server.services.user.verifyCurrentEmailOTP({
+ userId: req.permission.id,
+ otpCode: req.body.otpCode
+ });
+ return result;
+ }
+ });
+
server.route({
method: "PATCH",
url: "/me/email",
diff --git a/backend/src/services/auth-token/auth-token-service.ts b/backend/src/services/auth-token/auth-token-service.ts
index b1892d89ba..7dd298e5f9 100644
--- a/backend/src/services/auth-token/auth-token-service.ts
+++ b/backend/src/services/auth-token/auth-token-service.ts
@@ -42,7 +42,8 @@ export const getTokenConfig = (tokenType: TokenType) => {
const expiresAt = new Date(new Date().getTime() + 86400000);
return { token, triesLeft, expiresAt };
}
- case TokenType.TOKEN_EMAIL_CHANGE_OTP: {
+ case TokenType.TOKEN_EMAIL_CHANGE_OTP:
+ case TokenType.TOKEN_EMAIL_CHANGE_CURRENT_OTP: {
const token = String(crypto.randomInt(10 ** 5, 10 ** 6 - 1));
const triesLeft = 1;
const expiresAt = new Date(new Date().getTime() + 600000);
diff --git a/backend/src/services/auth-token/auth-token-types.ts b/backend/src/services/auth-token/auth-token-types.ts
index 75c3e8c98c..fd257809ca 100644
--- a/backend/src/services/auth-token/auth-token-types.ts
+++ b/backend/src/services/auth-token/auth-token-types.ts
@@ -4,6 +4,7 @@ export enum TokenType {
TOKEN_EMAIL_CONFIRMATION = "emailConfirmation",
TOKEN_EMAIL_VERIFICATION = "emailVerification", // unverified -> verified
TOKEN_EMAIL_CHANGE_OTP = "emailChangeOtp",
+ TOKEN_EMAIL_CHANGE_CURRENT_OTP = "emailChangeCurrentOtp",
TOKEN_EMAIL_MFA = "emailMfa",
TOKEN_EMAIL_ORG_INVITATION = "organizationInvitation",
TOKEN_EMAIL_PASSWORD_RESET = "passwordReset",
diff --git a/backend/src/services/smtp/emails/EmailChangeRequestNotificationTemplate.tsx b/backend/src/services/smtp/emails/EmailChangeRequestNotificationTemplate.tsx
new file mode 100644
index 0000000000..51baa20c7a
--- /dev/null
+++ b/backend/src/services/smtp/emails/EmailChangeRequestNotificationTemplate.tsx
@@ -0,0 +1,68 @@
+import { Heading, Section, Text } from "@react-email/components";
+import React from "react";
+
+import { BaseEmailWrapper, BaseEmailWrapperProps } from "./BaseEmailWrapper";
+import { BaseLink } from "./BaseLink";
+
+interface EmailChangeRequestNotificationTemplateProps
+ extends Omit<BaseEmailWrapperProps, "title" | "preview" | "children"> {
+ currentEmail: string;
+ requestedEmail: string;
+ code: string;
+ isCloud: boolean;
+}
+
+export const EmailChangeRequestNotificationTemplate = ({
+ currentEmail,
+ requestedEmail,
+ code,
+ siteUrl,
+ isCloud
+}: EmailChangeRequestNotificationTemplateProps) => {
+ return (
+ <BaseEmailWrapper
+ title="Confirm your Infisical email change"
+ preview="Confirm the email change requested on your Infisical account."
+ siteUrl={siteUrl}
+ >
+ <Heading className="text-black text-[18px] leading-[28px] text-center font-normal p-0 mx-0">
+ <strong>Confirm your email change</strong>
+ </Heading>
+ <Section className="px-[24px] mt-[36px] pt-[12px] pb-[8px] text-[14px] border border-solid border-gray-200 rounded-md bg-gray-50">
+ <Text className="text-[14px]">A request was made to change the email on your Infisical account.</Text>
+ <strong>Current email</strong>
+ <Text className="text-[14px] mt-[4px]">{currentEmail}</Text>
+ <strong>Requested new email</strong>
+ <Text className="text-[14px] mt-[4px]">{requestedEmail}</Text>
+ <Text className="text-[14px]">
+ Enter the confirmation code below to approve this change. After confirming, a separate code will be sent to
+ the new email address to finalize the change.
+ </Text>
+ <Text className="text-[24px] text-center mt-[16px]">
+ <strong>{code}</strong>
+ </Text>
+ </Section>
+ <Section className="mt-[24px] bg-gray-50 px-[24px] pt-[2px] pb-[16px] border border-solid border-gray-200 rounded-md text-gray-800">
+ <Text className="mb-[0px]">
+ <strong>If this wasn&apos;t you</strong>, do not enter the code and contact{" "}
+ {isCloud ? (
+ <BaseLink href="mailto:[email protected]">[email protected]</BaseLink>
+ ) : (
+ "your administrator"
+ )}{" "}
+ immediately. Without this code, the email cannot be changed.
+ </Text>
+ </Section>
+ </BaseEmailWrapper>
+ );
+};
+
+export default EmailChangeRequestNotificationTemplate;
+
+EmailChangeRequestNotificationTemplate.PreviewProps = {
+ currentEmail: "[email protected]",
+ requestedEmail: "[email protected]",
+ code: "124356",
+ isCloud: true,
+ siteUrl: "https://infisical.com"
+} as EmailChangeRequestNotificationTemplateProps;
diff --git a/backend/src/services/smtp/emails/index.ts b/backend/src/services/smtp/emails/index.ts
index a7425c2ae0..1ad962f87a 100644
--- a/backend/src/services/smtp/emails/index.ts
+++ b/backend/src/services/smtp/emails/index.ts
@@ -3,6 +3,7 @@ export * from "./AccessApprovalRequestUpdatedTemplate";
export * from "./AccountDeletionConfirmationTemplate";
export * from "./AuditLogMigrationAlertTemplate";
export * from "./CredentialRotationFailedTemplate";
+export * from "./EmailChangeRequestNotificationTemplate";
export * from "./EmailMfaTemplate";
export * from "./EmailVerificationTemplate";
export * from "./ExternalImportFailedTemplate";
diff --git a/backend/src/services/smtp/smtp-service.ts b/backend/src/services/smtp/smtp-service.ts
index 4dbadaf011..6fa1ca93a4 100644
--- a/backend/src/services/smtp/smtp-service.ts
+++ b/backend/src/services/smtp/smtp-service.ts
@@ -13,6 +13,7 @@ import {
AccountDeletionConfirmationTemplate,
AuditLogMigrationAlertTemplate,
CredentialRotationFailedTemplate,
+ EmailChangeRequestNotificationTemplate,
EmailMfaTemplate,
EmailVerificationTemplate,
ExternalImportFailedTemplate,
@@ -64,6 +65,7 @@ export enum SmtpTemplates {
SignupEmailVerification = "signupEmailVerification",
SignupExistingAccount = "signupExistingAccount",
EmailVerification = "emailVerification",
+ EmailChangeRequestNotification = "emailChangeRequestNotification",
SecretReminder = "secretReminder",
EmailMfa = "emailMfa",
UnlockAccount = "unlockAccount",
@@ -126,6 +128,7 @@ const EmailTemplateMap: Record<SmtpTemplates, React.FC<any>> = {
[SmtpTemplates.AccessApprovalRequest]: AccessApprovalRequestTemplate,
[SmtpTemplates.AccessApprovalRequestUpdated]: AccessApprovalRequestUpdatedTemplate,
[SmtpTemplates.EmailVerification]: EmailVerificationTemplate,
+ [SmtpTemplates.EmailChangeRequestNotification]: EmailChangeRequestNotificationTemplate,
[SmtpTemplates.ExternalImportFailed]: ExternalImportFailedTemplate,
[SmtpTemplates.ExternalImportStarted]: ExternalImportStartedTemplate,
[SmtpTemplates.ExternalImportSuccessful]: ExternalImportSucceededTemplate,
diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.ts
index 75351c2bb4..47f8c294f4 100644
--- a/backend/src/services/user/user-service.ts
+++ b/backend/src/services/user/user-service.ts
@@ -19,7 +19,7 @@ import { TGroupProjectDALFactory } from "../group-project/group-project-dal";
import { TMembershipUserDALFactory } from "../membership-user/membership-user-dal";
import { TUserAliasDALFactory } from "../user-alias/user-alias-dal";
import { TUserDALFactory } from "./user-dal";
-import { TListUserGroupsDTO, TUpdateUserEmailDTO, TUpdateUserMfaDTO } from "./user-types";
+import { TListUserGroupsDTO, TUpdateUserEmailDTO, TUpdateUserMfaDTO, TVerifyCurrentEmailOTPDTO } from "./user-types";
type TUserServiceFactoryDep = {
userDAL: Pick<
@@ -132,7 +132,14 @@ export const userServiceFactory = ({
throw new BadRequestError({ message: "LDAP auth method cannot be updated", name: "UpdateAuthMethods" });
}
- const updatedUser = await userDAL.updateById(userId, { authMethods });
+ // When email auth is removed, clear the stored password so no stale credential lingers.
+ // Re-enabling email auth later requires a fresh password via the setup flow.
+ const isRemovingEmailAuth = user.authMethods?.includes(AuthMethod.EMAIL) && !authMethods.includes(AuthMethod.EMAIL);
+
+ const updatedUser = await userDAL.updateById(userId, {
+ authMethods,
+ ...(isRemovingEmailAuth ? { hashedPassword: null } : {})
+ });
return updatedUser;
};
@@ -168,6 +175,13 @@ export const userServiceFactory = ({
throw new BadRequestError({ message: "Cannot update email for LDAP users", name: "RequestEmailChangeOTP" });
}
+ if (!user.email) {
+ throw new BadRequestError({
+ message: "Cannot change email: no current email address is set on this account.",
+ name: "RequestEmailChangeOTP"
+ });
+ }
+
const hasScimRestriction = await checkUserScimRestriction(userId, tx);
if (hasScimRestriction) {
throw new BadRequestError({
@@ -179,25 +193,27 @@ export const userServiceFactory = ({
// Silently check if another user already has this email - don't send OTP if email is taken
const existingUser = await userDAL.findOne({ username: normalizedNewEmail }, tx);
if (!existingUser) {
- // Generate 6-digit OTP
+ // Step 1 of 2: send OTP to the CURRENT email so the legitimate owner must approve
+ // the change before any code is sent to the new address.
const otpCode = await tokenService.createTokenForUser({
- type: TokenType.TOKEN_EMAIL_CHANGE_OTP,
+ type: TokenType.TOKEN_EMAIL_CHANGE_CURRENT_OTP,
userId,
payload: newEmail.toLowerCase()
});
- // Send OTP to NEW email address
await smtpService.sendMail({
- template: SmtpTemplates.EmailVerification,
- subjectLine: "Infisical email change verification",
- recipients: [newEmail.toLowerCase()],
+ template: SmtpTemplates.EmailChangeRequestNotification,
+ subjectLine: "Confirm your Infisical email change",
+ recipients: [user.email],
substitutions: {
+ currentEmail: user.email,
+ requestedEmail: newEmail.toLowerCase(),
code: otpCode
}
});
}
- return { success: true, message: "Verification code sent to new email address" };
+ return { success: true, message: "Verification code sent to current email address" };
});
// Force this function to have a minimum execution time of 2 seconds to avoid possible information disclosure about existing users
const endTime = new Date();
@@ -210,6 +226,66 @@ export const userServiceFactory = ({
return changeEmailOTP;
};
+ const verifyCurrentEmailOTP = async ({ userId, otpCode }: TVerifyCurrentEmailOTPDTO) => {
+ return userDAL.transaction(async (tx) => {
+ const user = await userDAL.findById(userId, tx);
+ if (!user)
+ throw new NotFoundError({ message: `User with ID '${userId}' not found`, name: "VerifyCurrentEmailOTP" });
+
+ if (user.authMethods?.includes(AuthMethod.LDAP)) {
+ throw new BadRequestError({ message: "Cannot update email for LDAP users", name: "VerifyCurrentEmailOTP" });
+ }
+
+ const hasScimRestriction = await checkUserScimRestriction(userId, tx);
+ if (hasScimRestriction) {
+ throw new BadRequestError({
+ message: "Email changes are disabled because SCIM is enabled for one or more of your organizations",
+ name: "VerifyCurrentEmailOTP"
+ });
+ }
+
+ let tokenData;
+ try {
+ tokenData = await tokenService.validateTokenForUser({
+ type: TokenType.TOKEN_EMAIL_CHANGE_CURRENT_OTP,
+ userId,
+ code: otpCode
+ });
+ } catch (error) {
+ throw new BadRequestError({ message: "Invalid verification code", name: "VerifyCurrentEmailOTP" });
+ }
+
+ const newEmail = tokenData?.payload;
+ if (!newEmail) {
+ throw new BadRequestError({ message: "Invalid verification code", name: "VerifyCurrentEmailOTP" });
+ }
+
+ // Re-check availability — someone else may have claimed this email since the request was issued
+ const existingUser = await userDAL.findOne({ username: newEmail }, tx);
+ if (existingUser) {
+ throw new BadRequestError({ message: "Email is no longer available", name: "VerifyCurrentEmailOTP" });
+ }
+
+ // Step 2 of 2: now that current-email control is proven, send OTP to the NEW address
+ const newEmailOtpCode = await tokenService.createTokenForUser({
+ type: TokenType.TOKEN_EMAIL_CHANGE_OTP,
+ userId,
+ payload: newEmail
+ });
+
+ await smtpService.sendMail({
+ template: SmtpTemplates.EmailVerification,
+ subjectLine: "Infisical email change verification",
+ recipients: [newEmail],
+ substitutions: {
+ code: newEmailOtpCode
+ }
+ });
+
+ return { success: true, newEmail };
+ });
+ };
+
const updateUserEmail = async ({
userId,
newEmail: unsanitizedEmail,
@@ -448,6 +524,7 @@ export const userServiceFactory = ({
updateUserName,
updateAuthMethods,
requestEmailChangeOTP,
+ verifyCurrentEmailOTP,
updateUserEmail,
deleteUser,
getMe,
diff --git a/backend/src/services/user/user-types.ts b/backend/src/services/user/user-types.ts
index 7a974a899b..ab107a1e2d 100644
--- a/backend/src/services/user/user-types.ts
+++ b/backend/src/services/user/user-types.ts
@@ -21,3 +21,8 @@ export type TUpdateUserEmailDTO = {
userId: string;
newEmail: string;
};
+
+export type TVerifyCurrentEmailOTPDTO = {
+ userId: string;
+ otpCode: string;
+};
diff --git a/frontend/src/hooks/api/users/index.tsx b/frontend/src/hooks/api/users/index.tsx
index fd03a2674e..672139e6e0 100644
--- a/frontend/src/hooks/api/users/index.tsx
+++ b/frontend/src/hooks/api/users/index.tsx
@@ -4,7 +4,8 @@ export {
useRequestEmailChangeOTP,
useRevokeMySessionById,
useSendEmailVerificationCode,
- useUpdateUserEmail
+ useUpdateUserEmail,
+ useVerifyCurrentEmailOTP
} from "./mutation";
export {
fetchOrgUsers,
diff --git a/frontend/src/hooks/api/users/mutation.tsx b/frontend/src/hooks/api/users/mutation.tsx
index 621a2fc7e4..12e4316eea 100644
--- a/frontend/src/hooks/api/users/mutation.tsx
+++ b/frontend/src/hooks/api/users/mutation.tsx
@@ -155,6 +155,18 @@ export const useRequestEmailChangeOTP = () => {
});
};
+export const useVerifyCurrentEmailOTP = () => {
+ return useMutation({
+ mutationFn: async ({ otpCode }: { otpCode: string }) => {
+ const { data } = await apiRequest.post<{ success: boolean; newEmail: string }>(
+ "/api/v2/users/me/email-change/verify-current",
+ { otpCode }
+ );
+ return data;
+ }
+ });
+};
+
export const useUpdateUserEmail = () => {
const queryClient = useQueryClient();
return useMutation({
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx
index a6e5e33a9c..c3f52ba339 100644
--- a/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx
@@ -8,7 +8,11 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, Input, Modal, ModalContent } from "@app/components/v2";
import { useUser } from "@app/context";
-import { useRequestEmailChangeOTP, useUpdateUserEmail } from "@app/hooks/api/users";
+import {
+ useRequestEmailChangeOTP,
+ useUpdateUserEmail,
+ useVerifyCurrentEmailOTP
+} from "@app/hooks/api/users";
import { clearSession } from "@app/hooks/api/users/queries";
import { AuthMethod } from "@app/hooks/api/users/types";
@@ -41,12 +45,15 @@ const otpInputProps = {
}
};
+type OtpStep = "currentEmail" | "newEmail";
+
export const ChangeEmailSection = () => {
const navigate = useNavigate();
const { user } = useUser();
const hasEmailAuth = user?.authMethods?.includes(AuthMethod.EMAIL) ?? false;
- const [isOTPModalOpen, setIsOTPModalOpen] = useState(false);
+ const [otpStep, setOtpStep] = useState<OtpStep | null>(null);
const [pendingEmail, setPendingEmail] = useState("");
+ const [typedOTP, setTypedOTP] = useState("");
const emailForm = useForm<EmailFormData>({
defaultValues: { newEmail: "" },
@@ -55,16 +62,16 @@ export const ChangeEmailSection = () => {
const { mutateAsync: requestEmailChangeOTP, isPending: isRequestingOTP } =
useRequestEmailChangeOTP();
+ const { mutateAsync: verifyCurrentEmailOTP, isPending: isVerifyingCurrent } =
+ useVerifyCurrentEmailOTP();
const { mutateAsync: updateUserEmail, isPending: isUpdatingEmail } = useUpdateUserEmail();
- // Watch the email field to enable/disable the button
const watchedEmail = useWatch({
control: emailForm.control,
name: "newEmail",
defaultValue: ""
});
- // Helper function to check if email is valid
const isEmailValid = (email: string): boolean => {
try {
emailSchema.parse({ newEmail: email });
@@ -74,6 +81,17 @@ export const ChangeEmailSection = () => {
}
};
+ const closeOtpModal = () => {
+ setOtpStep(null);
+ setTypedOTP("");
+ };
+
+ const resetFlow = () => {
+ closeOtpModal();
+ setPendingEmail("");
+ emailForm.reset();
+ };
+
const handleEmailSubmit = async ({ newEmail }: EmailFormData) => {
if (newEmail.toLowerCase() === user?.email?.toLowerCase()) {
createNotification({
@@ -83,19 +101,27 @@ export const ChangeEmailSection = () => {
return;
}
- await requestEmailChangeOTP({ newEmail });
+ try {
+ await requestEmailChangeOTP({ newEmail });
+ } catch (err: any) {
+ createNotification({
+ text: err?.response?.data?.message || "Failed to request verification code",
+ type: "error"
+ });
+ return;
+ }
+
setPendingEmail(newEmail);
- setIsOTPModalOpen(true);
+ setTypedOTP("");
+ setOtpStep("currentEmail");
createNotification({
- text: "Verification code sent to your new email address. Check your inbox!",
+ text: "Verification code sent to your current email address. Check your inbox!",
type: "success"
});
};
- const [typedOTP, setTypedOTP] = useState("");
-
- const handleOTPSubmit = async () => {
+ const handleCurrentOtpSubmit = async () => {
if (typedOTP.length !== 6) {
createNotification({
text: "Please enter the complete 6-digit verification code",
@@ -105,49 +131,70 @@ export const ChangeEmailSection = () => {
}
try {
- await updateUserEmail({ newEmail: pendingEmail, otpCode: typedOTP });
+ await verifyCurrentEmailOTP({ otpCode: typedOTP });
+ } catch (err: any) {
+ const errorMessage = err?.response?.data?.message || "Invalid verification code";
+ createNotification({ text: errorMessage, type: "error" });
+ if (errorMessage.includes("Invalid verification code")) {
+ resetFlow();
+ }
+ return;
+ }
- createNotification({
- text: "Email updated successfully. You will be redirected to login.",
- type: "success"
- });
+ setTypedOTP("");
+ setOtpStep("newEmail");
- // Reset forms and close modal
- emailForm.reset();
- setIsOTPModalOpen(false);
- setPendingEmail("");
- setTypedOTP("");
+ createNotification({
+ text: "Confirmed. A second verification code has been sent to your new email address.",
+ type: "success"
+ });
+ };
- // Clear frontend session/token to ensure proper logout
- clearSession();
+ const handleNewOtpSubmit = async () => {
+ if (typedOTP.length !== 6) {
+ createNotification({
+ text: "Please enter the complete 6-digit verification code",
+ type: "error"
+ });
+ return;
+ }
- // Redirect to login after a short delay
- setTimeout(() => {
- navigate({ to: "/login" });
- }, 2000);
+ try {
+ await updateUserEmail({ newEmail: pendingEmail, otpCode: typedOTP });
} catch (err: any) {
const errorMessage = err?.response?.data?.message || "Invalid verification code";
+ createNotification({ text: errorMessage, type: "error" });
if (errorMessage.includes("Invalid verification code")) {
- // Reset to email step so user must request new OTP
- setIsOTPModalOpen(false);
- setPendingEmail("");
- setTypedOTP("");
- emailForm.reset();
-
- createNotification({
- text: "Invalid verification code. Please request a new one.",
- type: "error"
- });
+ resetFlow();
}
+ return;
}
- };
- const handleOTPModalClose = () => {
- setIsOTPModalOpen(false);
- setPendingEmail("");
- setTypedOTP("");
+ createNotification({
+ text: "Email updated successfully. You will be redirected to login.",
+ type: "success"
+ });
+
+ resetFlow();
+ clearSession();
+
+ setTimeout(() => {
+ navigate({ to: "/login" });
+ }, 2000);
};
+ const isOtpModalOpen = otpStep !== null;
+ const otpRecipient = otpStep === "currentEmail" ? (user?.email ?? "") : pendingEmail;
+ const otpSubTitle =
+ otpStep === "currentEmail"
+ ? `Enter the 6-digit code sent to your current email: ${otpRecipient}`
+ : `Enter the 6-digit code sent to your new email: ${otpRecipient}`;
+ const otpTitle =
+ otpStep === "currentEmail" ? "Confirm from current email" : "Confirm from new email";
+ const otpButtonLabel = otpStep === "currentEmail" ? "Confirm" : "Confirm Email Change";
+ const isOtpSubmitLoading = otpStep === "currentEmail" ? isVerifyingCurrent : isUpdatingEmail;
+ const onOtpSubmit = otpStep === "currentEmail" ? handleCurrentOtpSubmit : handleNewOtpSubmit;
+
return (
<>
<div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
@@ -188,24 +235,23 @@ export const ChangeEmailSection = () => {
Send Verification Code
</Button>
<p className="mt-2 font-inter text-sm text-mineshaft-400">
- We&apos;ll send an 6-digit verification code to your new email address.
+ We&apos;ll first send a 6-digit code to your current email to confirm the change. After
+ you approve, a second code will be sent to your new email to finalize it.
</p>
</form>
</div>
<Modal
- isOpen={isOTPModalOpen}
+ isOpen={isOtpModalOpen}
onOpenChange={(isOpen) => {
- if (!isOpen) handleOTPModalClose();
+ if (!isOpen) closeOtpModal();
}}
>
- <ModalContent
- title="Email Verification"
- subTitle={`Enter the 6-digit verification code sent to: ${pendingEmail}`}
- >
+ <ModalContent title={otpTitle} subTitle={otpSubTitle}>
<div className="flex flex-col items-center space-y-4">
<div className="flex justify-center">
<ReactCodeInput
+ key={otpStep ?? "closed"}
name="otp-input"
inputMode="tel"
type="text"
@@ -217,15 +263,15 @@ export const ChangeEmailSection = () => {
/>
</div>
<div className="flex gap-2">
- <Button colorSchema="secondary" variant="outline" onClick={handleOTPModalClose}>
+ <Button colorSchema="secondary" variant="outline" onClick={closeOtpModal}>
Cancel
</Button>
<Button
- onClick={handleOTPSubmit}
- isLoading={isUpdatingEmail}
- isDisabled={typedOTP.length !== 6}
+ onClick={onOtpSubmit}
+ isLoading={isOtpSubmitLoading}
+ isDisabled={typedOTP.length !== 6 || isOtpSubmitLoading}
>
- Confirm Email Change
+ {otpButtonLabel}
</Button>
</div>
</div>