Files
zitadel/apps/login/src/components/set-password-form.tsx
T
Matías RacedoandGitHub 78be618357 fix(login): translate authentication and OTP strings (#12668)
Closes #12481
Closes #12226

# Which Problems Are Solved

Login V2 still contained several hardcoded authentication-method and OTP
strings, preventing them from following the selected locale or being
overridden through custom Login translations.

Additionally, the password-reset flow already referenced
`password.errors.passwordResetNotAllowed`, but the key was missing from
the Login V2 translations, causing the raw translation key to be
displayed when password reset is disabled.

# How the Problems Are Solved

* Replaced the hardcoded authentication-method labels with Login V2
translation keys.
* Replaced the OTP challenge and verification fallback messages with
translated values.
* Reused the existing `otp.verify.resendCode` translation for the resend
button's accessible label.
* Added `password.errors.passwordResetNotAllowed`.
* Added the new keys to all supported Login V2 locales and mirrored them
in `internal/query/v2-default.json` so frontend and API-provided default
translations remain consistent.
* Added unit coverage for the translated authentication labels and OTP
failure paths.

# How the Changes Are Tested

* `pnpm nx run @zitadel/login:test-unit`
* `pnpm nx run @zitadel/login:lint`
* `pnpm nx run @zitadel/login:build`
* `pnpm nx run-many --projects @zitadel/login @zitadel/client
@zitadel/proto --targets lint build test`
* Manually verified Login V2 with multiple locales, including
authentication-method labels, OTP failure fallbacks, and the disabled
password-reset flow.
2026-09-03 06:01:34 +02:00

278 lines
8.6 KiB
TypeScript

"use client";
import { lowerCaseValidator, numberValidator, symbolValidator, upperCaseValidator } from "@/helpers/validators";
import { handleServerActionResponse } from "@/lib/client-utils";
import { changePassword, resetPassword, sendPassword } from "@/lib/server/password";
import { create } from "@zitadel/client";
import { ChecksSchema } from "@zitadel/proto/zitadel/session/v2/session_service_pb";
import { PasswordComplexitySettings } from "@zitadel/proto/zitadel/settings/v2/password_settings_pb";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { FieldValues, useForm } from "react-hook-form";
import { Alert, AlertType } from "./alert";
import { AutoSubmitForm } from "./auto-submit-form";
import { BackButton } from "./back-button";
import { Button, ButtonVariants } from "./button";
import { TextInput } from "./input";
import { PasswordComplexity } from "./password-complexity";
import { Spinner } from "./spinner";
import { Translated } from "./translated";
type Inputs =
| {
code: string;
password: string;
confirmPassword: string;
}
| FieldValues;
type Props = {
code?: string;
passwordComplexitySettings: PasswordComplexitySettings;
loginName: string;
userId: string;
organization?: string;
defaultOrganization?: string;
requestId?: string;
codeRequired: boolean;
};
export function SetPasswordForm({
passwordComplexitySettings,
organization,
defaultOrganization,
requestId,
loginName,
userId,
code,
codeRequired,
}: Props) {
const { register, handleSubmit, watch, formState } = useForm<Inputs>({
mode: "onChange",
defaultValues: {
code: code ?? "",
},
});
const t = useTranslations("password");
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<string>("");
const [samlData, setSamlData] = useState<{ url: string; fields: Record<string, string> } | null>(null);
const router = useRouter();
async function resendCode() {
setError("");
setLoading(true);
const response = await resetPassword({
loginName,
organization,
defaultOrganization,
requestId,
})
.catch(() => {
setError(t("set.errors.couldNotResetPassword"));
return;
})
.finally(() => {
setLoading(false);
});
if (response && "error" in response && typeof response.error === "string") {
setError(response.error);
return;
}
}
async function submitPassword(values: Inputs) {
setLoading(true);
let payload: { userId: string; password: string; code?: string; organization?: string } = {
userId: userId,
password: values.password,
organization,
};
// this is not required for initial password setup
if (codeRequired) {
payload = { ...payload, code: values.code };
}
const changeResponse = await changePassword(payload).catch(() => {
setError(t("set.errors.couldNotSetPassword"));
setLoading(false);
return;
});
if (changeResponse && "error" in changeResponse) {
setLoading(false);
setError(changeResponse.error);
return;
}
if (!changeResponse) {
setLoading(false);
setError(t("set.errors.couldNotSetPassword"));
return;
}
const params = new URLSearchParams({});
if (loginName) {
params.append("loginName", loginName);
}
if (organization) {
params.append("organization", organization);
}
await new Promise((resolve) => setTimeout(resolve, 2000)); // Wait for a second to avoid eventual consistency issues with an initial password being set
const passwordResponse = await sendPassword({
loginName,
organization,
checks: create(ChecksSchema, {
password: { password: values.password },
}),
requestId,
}).catch(() => {
setError(t("set.errors.couldNotVerifyPassword"));
setLoading(false);
return;
});
setLoading(false);
handleServerActionResponse(passwordResponse as any, router, setSamlData, setError);
return;
}
const { errors } = formState;
const watchPassword = watch("password", "");
const watchConfirmPassword = watch("confirmPassword", "");
const hasMinLength = passwordComplexitySettings && watchPassword?.length >= passwordComplexitySettings.minLength;
const hasSymbol = symbolValidator(watchPassword);
const hasNumber = numberValidator(watchPassword);
const hasUppercase = upperCaseValidator(watchPassword);
const hasLowercase = lowerCaseValidator(watchPassword);
const policyIsValid =
passwordComplexitySettings &&
(passwordComplexitySettings.requiresLowercase ? hasLowercase : true) &&
(passwordComplexitySettings.requiresNumber ? hasNumber : true) &&
(passwordComplexitySettings.requiresUppercase ? hasUppercase : true) &&
(passwordComplexitySettings.requiresSymbol ? hasSymbol : true) &&
hasMinLength;
return (
<>
{samlData && <AutoSubmitForm url={samlData.url} fields={samlData.fields} />}
<form className="w-full">
<div className="mb-4 grid grid-cols-1 gap-4 pt-4">
<input
type="text"
name="username"
autoComplete="username"
value={loginName}
readOnly
tabIndex={-1}
aria-hidden="true"
className="sr-only"
/>
{codeRequired && (
<Alert type={AlertType.INFO}>
<div className="flex flex-row">
<span className="mr-auto flex-1 text-left">
<Translated i18nKey="set.noCodeReceived" namespace="password" />
</span>
<button
aria-label={t("set.resend")}
disabled={loading}
type="button"
className="text-primary-light-500 hover:text-primary-light-400 dark:text-primary-dark-500 hover:dark:text-primary-dark-400 ml-4 cursor-pointer disabled:cursor-default disabled:text-gray-400 dark:disabled:text-gray-700"
onClick={() => {
resendCode();
}}
data-testid="resend-button"
>
<Translated i18nKey="set.resend" namespace="password" />
</button>
</div>
</Alert>
)}
{codeRequired && (
<div>
<TextInput
type="text"
autoFocus
required
{...register("code", {
required: t("set.required.code"),
})}
label={t("set.labels.code")}
autoComplete="one-time-code"
error={errors.code?.message as string}
data-testid="code-text-input"
/>
</div>
)}
<div>
<TextInput
type="password"
autoComplete="new-password"
autoFocus={!codeRequired}
required
{...register("password", {
required: t("set.required.newPassword"),
})}
label={t("set.labels.newPassword")}
error={errors.password?.message as string}
data-testid="password-set-text-input"
/>
</div>
<div>
<TextInput
type="password"
required
autoComplete="new-password"
{...register("confirmPassword", {
required: t("set.required.confirmPassword"),
})}
label={t("set.labels.confirmPassword")}
error={errors.confirmPassword?.message as string}
data-testid="password-set-confirm-text-input"
/>
</div>
</div>
{passwordComplexitySettings && (
<PasswordComplexity
passwordComplexitySettings={passwordComplexitySettings}
password={watchPassword}
equals={!!watchPassword && watchPassword === watchConfirmPassword}
/>
)}
{error && <Alert>{error}</Alert>}
<div className="mt-8 flex w-full flex-row items-center justify-between">
<BackButton data-testid="back-button" />
<Button
type="submit"
variant={ButtonVariants.Primary}
disabled={loading || !policyIsValid || !formState.isValid || watchPassword !== watchConfirmPassword}
onClick={handleSubmit(submitPassword)}
data-testid="submit-button"
>
{loading && <Spinner className="mr-2 h-5 w-5" />} <Translated i18nKey="set.submit" namespace="password" />
</Button>
</div>
</form>
</>
);
}