feat(auth): add registration and verification browser flow
This commit is contained in:
1 parent
391af7a1ef
commit
b2322bc178
41 files changed
+2144
-81
No files matched your search
@@ -0,0 +1 @@
|
||||
export { ConfirmEmailForm } from "./ui/confirm-email-form";
|
||||
@@ -0,0 +1,76 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
consumeVerificationToken,
|
||||
watchVerificationTokenChanges,
|
||||
type VerificationLinkBrowser,
|
||||
} from "./consume-verification-token";
|
||||
|
||||
function historyRecorder() {
|
||||
const replaceState = vi.fn();
|
||||
return { history: { state: { key: "route" }, replaceState }, replaceState };
|
||||
}
|
||||
|
||||
describe("consumeVerificationToken", () => {
|
||||
it("returns a valid token and removes the fragment while preserving the path and query", () => {
|
||||
const { history, replaceState } = historyRecorder();
|
||||
const token = "A".repeat(64);
|
||||
|
||||
expect(
|
||||
consumeVerificationToken(
|
||||
{ hash: `#token=${token}`, pathname: "/verify-email", search: "?source=mail" },
|
||||
history,
|
||||
),
|
||||
).toBe(token);
|
||||
expect(replaceState).toHaveBeenCalledWith(history.state, "", "/verify-email?source=mail");
|
||||
});
|
||||
|
||||
it("clears malformed and missing tokens without returning them", () => {
|
||||
for (const hash of ["#token=short", "#other=value", ""]) {
|
||||
const { history, replaceState } = historyRecorder();
|
||||
expect(
|
||||
consumeVerificationToken({ hash, pathname: "/verify-email", search: "" }, history),
|
||||
).toBeNull();
|
||||
expect(replaceState).toHaveBeenCalledWith(history.state, "", "/verify-email");
|
||||
}
|
||||
});
|
||||
|
||||
it("consumes and removes each new link fragment opened on the same page", () => {
|
||||
let hash = "";
|
||||
const listeners = new Set<() => void>();
|
||||
const state = { key: "route" };
|
||||
const browser: VerificationLinkBrowser = {
|
||||
location: {
|
||||
get hash() {
|
||||
return hash;
|
||||
},
|
||||
pathname: "/verify-email",
|
||||
search: "",
|
||||
},
|
||||
history: {
|
||||
state,
|
||||
replaceState: vi.fn((_state, _title, url) => {
|
||||
hash = new URL(String(url), "https://app.test").hash;
|
||||
}),
|
||||
},
|
||||
addEventListener: vi.fn((_type, listener) => listeners.add(listener)),
|
||||
removeEventListener: vi.fn((_type, listener) => listeners.delete(listener)),
|
||||
};
|
||||
const onTokenChange = vi.fn();
|
||||
const stopWatching = watchVerificationTokenChanges(browser, onTokenChange);
|
||||
const firstToken = "A".repeat(64);
|
||||
const secondToken = "B".repeat(64);
|
||||
|
||||
hash = `#token=${firstToken}`;
|
||||
for (const listener of listeners) listener();
|
||||
expect(onTokenChange).toHaveBeenLastCalledWith(firstToken);
|
||||
expect(hash).toBe("");
|
||||
|
||||
hash = `#token=${secondToken}`;
|
||||
for (const listener of listeners) listener();
|
||||
expect(onTokenChange).toHaveBeenLastCalledWith(secondToken);
|
||||
expect(hash).toBe("");
|
||||
|
||||
stopWatching();
|
||||
expect(listeners.size).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { VerificationToken } from "../../../shared/api/schemas";
|
||||
|
||||
type BrowserLocation = Pick<Location, "hash" | "pathname" | "search">;
|
||||
type BrowserHistory = Pick<History, "state" | "replaceState">;
|
||||
|
||||
export type VerificationLinkBrowser = {
|
||||
location: BrowserLocation;
|
||||
history: BrowserHistory;
|
||||
addEventListener: (type: "hashchange", listener: () => void) => void;
|
||||
removeEventListener: (type: "hashchange", listener: () => void) => void;
|
||||
};
|
||||
|
||||
/** Read the token once, then remove the full fragment from the visible history entry. */
|
||||
export function consumeVerificationToken(
|
||||
location: BrowserLocation,
|
||||
history: BrowserHistory,
|
||||
): string | null {
|
||||
const fragment = location.hash.startsWith("#") ? location.hash.slice(1) : location.hash;
|
||||
const rawToken = new URLSearchParams(fragment).get("token");
|
||||
history.replaceState(history.state, "", `${location.pathname}${location.search}`);
|
||||
return rawToken && VerificationToken.safeParse(rawToken).success ? rawToken : null;
|
||||
}
|
||||
|
||||
/** Listen for a verification link opened in the same tab after the first fragment was consumed. */
|
||||
export function watchVerificationTokenChanges(
|
||||
browser: VerificationLinkBrowser,
|
||||
onTokenChange: (token: string | null) => void,
|
||||
): () => void {
|
||||
const handleHashChange = () => {
|
||||
if (!browser.location.hash) return;
|
||||
onTokenChange(consumeVerificationToken(browser.location, browser.history));
|
||||
};
|
||||
browser.addEventListener("hashchange", handleHashChange);
|
||||
return () => browser.removeEventListener("hashchange", handleHashChange);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
.form {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.label {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.input {
|
||||
width: 100%;
|
||||
min-height: 2.75rem;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.input[aria-invalid="true"] {
|
||||
border-color: var(--color-danger);
|
||||
}
|
||||
|
||||
.hint,
|
||||
.error {
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.hint {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.error,
|
||||
.alert {
|
||||
color: var(--color-danger);
|
||||
}
|
||||
|
||||
.alert {
|
||||
padding: var(--space-3);
|
||||
border-left: var(--line-strong) solid var(--color-danger);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.status {
|
||||
min-height: 1.5em;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.notice {
|
||||
padding: var(--space-4);
|
||||
border-left: var(--line-strong) solid var(--color-accent);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState, type FormEvent } from "react";
|
||||
import { useConfirmEmail } from "../../../shared/api/endpoints/identity/identity";
|
||||
import { Button, ButtonLink, TextLink } from "../../../shared/ui";
|
||||
import { paths } from "../../../shared/config";
|
||||
import {
|
||||
consumeVerificationToken,
|
||||
watchVerificationTokenChanges,
|
||||
} from "../model/consume-verification-token";
|
||||
import styles from "./confirm-email-form.module.css";
|
||||
|
||||
function confirmationError(error: unknown): { message: string; expired: boolean } {
|
||||
const code = error instanceof Error && "code" in error ? String(error.code) : "";
|
||||
if (code === "verification_token_expired") {
|
||||
return { message: "Срок действия ссылки истек. Запросите новое письмо.", expired: true };
|
||||
}
|
||||
if (code === "verification_token_invalid") {
|
||||
return {
|
||||
message:
|
||||
"Не удалось подтвердить почту. Проверьте введенные данные и попробуйте еще раз или запросите новое письмо.",
|
||||
expired: false,
|
||||
};
|
||||
}
|
||||
if (code === "rate_limited") {
|
||||
return { message: "Слишком много попыток. Подождите и повторите попытку.", expired: false };
|
||||
}
|
||||
if (code === "csrf_check_failed") {
|
||||
return {
|
||||
message: "Не удалось проверить источник запроса. Обновите страницу и повторите попытку.",
|
||||
expired: false,
|
||||
};
|
||||
}
|
||||
return {
|
||||
message: "Не удалось подтвердить почту. Проверьте соединение и повторите попытку.",
|
||||
expired: false,
|
||||
};
|
||||
}
|
||||
|
||||
type ConfirmEmailFormProps = {
|
||||
onResendNeeded: () => void;
|
||||
onTokenReady: () => void;
|
||||
onConfirmed: () => void;
|
||||
};
|
||||
|
||||
export function ConfirmEmailForm({
|
||||
onResendNeeded,
|
||||
onTokenReady,
|
||||
onConfirmed,
|
||||
}: ConfirmEmailFormProps) {
|
||||
const tokenRef = useRef<string | null>(null);
|
||||
const initialFragmentConsumedRef = useRef(false);
|
||||
const tokenGenerationRef = useRef(0);
|
||||
const {
|
||||
isPending: isConfirmPending,
|
||||
mutateAsync,
|
||||
reset,
|
||||
} = useConfirmEmail({
|
||||
mutation: { gcTime: 0 },
|
||||
});
|
||||
const [ready, setReady] = useState(false);
|
||||
const [hasToken, setHasToken] = useState(false);
|
||||
const [password, setPassword] = useState("");
|
||||
const [passwordError, setPasswordError] = useState<string | null>(null);
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
|
||||
const handleTokenChange = useCallback(
|
||||
(token: string | null) => {
|
||||
tokenGenerationRef.current += 1;
|
||||
tokenRef.current = token;
|
||||
reset();
|
||||
setHasToken(token !== null);
|
||||
setPassword("");
|
||||
setPasswordError(null);
|
||||
setFormError(null);
|
||||
setConfirmed(false);
|
||||
if (token) onTokenReady();
|
||||
else onResendNeeded();
|
||||
},
|
||||
[onResendNeeded, onTokenReady, reset],
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!initialFragmentConsumedRef.current) {
|
||||
initialFragmentConsumedRef.current = true;
|
||||
tokenRef.current = consumeVerificationToken(window.location, window.history);
|
||||
setHasToken(tokenRef.current !== null);
|
||||
setReady(true);
|
||||
if (tokenRef.current) onTokenReady();
|
||||
else onResendNeeded();
|
||||
}
|
||||
return watchVerificationTokenChanges(window, handleTokenChange);
|
||||
}, [handleTokenChange, onResendNeeded, onTokenReady]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
tokenGenerationRef.current += 1;
|
||||
reset();
|
||||
},
|
||||
[reset],
|
||||
);
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
const token = tokenRef.current;
|
||||
if (!token || isConfirmPending) return;
|
||||
const generation = tokenGenerationRef.current;
|
||||
|
||||
const passwordLength = Array.from(password.normalize("NFKC")).length;
|
||||
if (passwordLength < 1 || passwordLength > 128) {
|
||||
setPasswordError(
|
||||
"Введите пароль регистрации длиной от 1 до 128 символов после нормализации.",
|
||||
);
|
||||
setFormError(null);
|
||||
return;
|
||||
}
|
||||
|
||||
setPasswordError(null);
|
||||
setFormError(null);
|
||||
try {
|
||||
await mutateAsync({ data: { token, password } });
|
||||
if (generation !== tokenGenerationRef.current) return;
|
||||
reset();
|
||||
tokenRef.current = null;
|
||||
setHasToken(false);
|
||||
setPassword("");
|
||||
setConfirmed(true);
|
||||
onConfirmed();
|
||||
} catch (error: unknown) {
|
||||
if (generation !== tokenGenerationRef.current) return;
|
||||
reset();
|
||||
const result = confirmationError(error);
|
||||
setFormError(result.message);
|
||||
if (result.expired) {
|
||||
tokenRef.current = null;
|
||||
setHasToken(false);
|
||||
setPassword("");
|
||||
onResendNeeded();
|
||||
} else if (
|
||||
error instanceof Error &&
|
||||
"code" in error &&
|
||||
error.code === "verification_token_invalid"
|
||||
) {
|
||||
setPassword("");
|
||||
onResendNeeded();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!ready) {
|
||||
return (
|
||||
<p className={styles.status} role="status">
|
||||
Открываем безопасную ссылку...
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
if (confirmed) {
|
||||
return (
|
||||
<div className={styles.form}>
|
||||
<div className={styles.notice} role="status" aria-live="polite">
|
||||
Почта подтверждена. Войдите с паролем, который вы выбрали при регистрации. После входа
|
||||
сервис откроет сохраненный шаг.
|
||||
</div>
|
||||
<ButtonLink to={paths.login}>Перейти ко входу</ButtonLink>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!hasToken) {
|
||||
return (
|
||||
<div className={styles.form}>
|
||||
{formError ? (
|
||||
<p className={styles.alert} role="alert">
|
||||
{formError}
|
||||
</p>
|
||||
) : (
|
||||
<p className={styles.hint}>
|
||||
В ссылке нет действующего токена. Укажите адрес, чтобы запросить новое письмо.
|
||||
</p>
|
||||
)}
|
||||
<TextLink to={paths.login}>Перейти ко входу</TextLink>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.form}>
|
||||
{formError ? (
|
||||
<p className={styles.alert} role="alert">
|
||||
{formError}
|
||||
</p>
|
||||
) : null}
|
||||
<form onSubmit={(event) => void submit(event)} noValidate>
|
||||
<div className={styles.form}>
|
||||
<div className={styles.field}>
|
||||
<label className={styles.label} htmlFor="verification-password">
|
||||
Пароль, выбранный при регистрации
|
||||
</label>
|
||||
<input
|
||||
className={styles.input}
|
||||
id="verification-password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
required
|
||||
maxLength={512}
|
||||
value={password}
|
||||
disabled={isConfirmPending}
|
||||
aria-invalid={Boolean(passwordError)}
|
||||
aria-describedby={
|
||||
passwordError ? "verification-password-error" : "verification-password-hint"
|
||||
}
|
||||
onChange={(event) => {
|
||||
setPassword(event.currentTarget.value);
|
||||
setPasswordError(null);
|
||||
setFormError(null);
|
||||
}}
|
||||
/>
|
||||
{passwordError ? (
|
||||
<p className={styles.error} id="verification-password-error">
|
||||
{passwordError}
|
||||
</p>
|
||||
) : (
|
||||
<p className={styles.hint} id="verification-password-hint">
|
||||
Для подтверждения нужно ввести пароль, указанный в этой регистрации.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className={styles.actions}>
|
||||
<Button type="submit" isBusy={isConfirmPending}>
|
||||
{isConfirmPending ? "Подтверждаем..." : "Подтвердить почту"}
|
||||
</Button>
|
||||
<TextLink to={paths.login}>Уже подтвердили? Войти</TextLink>
|
||||
</div>
|
||||
<p className={styles.status} role="status" aria-live="polite">
|
||||
{isConfirmPending ? "Проверяем ссылку..." : ""}
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { RegisterForm } from "./ui/register-form";
|
||||
export type { RegistrationDraft } from "./ui/register-form";
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { validateNewPassword, validateRegistration } from "./validation";
|
||||
|
||||
describe("registration validation", () => {
|
||||
it("counts NFKC-normalized Unicode code points", () => {
|
||||
expect(validateNewPassword("😀".repeat(15))).toBeUndefined();
|
||||
expect(validateNewPassword("12345678901234")).toContain("не менее 15");
|
||||
expect(validateNewPassword("😀".repeat(129))).toContain("не более 128");
|
||||
});
|
||||
|
||||
it("requires a valid address, scenario, and separately accepted consent", () => {
|
||||
expect(
|
||||
validateRegistration({
|
||||
email: "person@example.test",
|
||||
password: "a secure phrase with enough length",
|
||||
scenario: "candidate",
|
||||
acceptedConsent: true,
|
||||
}),
|
||||
).toEqual({});
|
||||
|
||||
expect(
|
||||
validateRegistration({
|
||||
email: "not-an-email",
|
||||
password: "a secure phrase with enough length",
|
||||
scenario: "",
|
||||
acceptedConsent: false,
|
||||
}),
|
||||
).toEqual({
|
||||
email: "Введите корректный адрес электронной почты.",
|
||||
scenario: "Выберите сценарий.",
|
||||
consent: "Подтвердите согласие после прочтения текста.",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { EmailAddress } from "../../../shared/api/schemas";
|
||||
|
||||
export type RegistrationErrors = {
|
||||
email?: string;
|
||||
password?: string;
|
||||
scenario?: string;
|
||||
consent?: string;
|
||||
};
|
||||
|
||||
/** Apply the server's NFKC and Unicode code-point length rules before sending. */
|
||||
export function validateNewPassword(password: string): string | undefined {
|
||||
const length = Array.from(password.normalize("NFKC")).length;
|
||||
if (length < 15) {
|
||||
return "Введите не менее 15 символов после нормализации.";
|
||||
}
|
||||
if (length > 128) {
|
||||
return "Введите не более 128 символов после нормализации.";
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function validateRegistration(input: {
|
||||
email: string;
|
||||
password: string;
|
||||
scenario: string;
|
||||
acceptedConsent: boolean;
|
||||
}): RegistrationErrors {
|
||||
const errors: RegistrationErrors = {};
|
||||
if (!EmailAddress.safeParse(input.email).success) {
|
||||
errors.email = "Введите корректный адрес электронной почты.";
|
||||
}
|
||||
const passwordError = validateNewPassword(input.password);
|
||||
if (passwordError) {
|
||||
errors.password = passwordError;
|
||||
}
|
||||
if (input.scenario !== "candidate" && input.scenario !== "employer") {
|
||||
errors.scenario = "Выберите сценарий.";
|
||||
}
|
||||
if (!input.acceptedConsent) {
|
||||
errors.consent = "Подтвердите согласие после прочтения текста.";
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
.form {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.label {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.input {
|
||||
width: 100%;
|
||||
min-height: 2.75rem;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.input[aria-invalid="true"] {
|
||||
border-color: var(--color-danger);
|
||||
}
|
||||
|
||||
.hint,
|
||||
.error,
|
||||
.choice-description {
|
||||
color: var(--color-text-secondary);
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.error {
|
||||
color: var(--color-danger);
|
||||
}
|
||||
|
||||
.choices {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
}
|
||||
|
||||
.choices legend {
|
||||
padding-inline: var(--space-2);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.choice {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
gap: var(--space-3);
|
||||
align-items: start;
|
||||
min-width: 0;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-s);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.choice input {
|
||||
width: 1.1rem;
|
||||
height: 1.1rem;
|
||||
margin-top: 0.2rem;
|
||||
accent-color: var(--color-accent);
|
||||
}
|
||||
|
||||
.choice-body {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.consent {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-4);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-m);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.consent-title {
|
||||
font-size: var(--font-size-m);
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.consent-text {
|
||||
max-height: 16rem;
|
||||
overflow: auto;
|
||||
padding: var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-divider);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-canvas);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.consent-choice {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
gap: var(--space-3);
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.consent-choice input {
|
||||
width: 1.1rem;
|
||||
height: 1.1rem;
|
||||
margin-top: 0.2rem;
|
||||
accent-color: var(--color-accent);
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.notice {
|
||||
padding: var(--space-4);
|
||||
border-left: var(--line-strong) solid var(--color-accent);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.notice p + p {
|
||||
margin-top: var(--space-2);
|
||||
}
|
||||
|
||||
.alert {
|
||||
padding: var(--space-3);
|
||||
border-left: var(--line-strong) solid var(--color-danger);
|
||||
background: var(--color-surface);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.status {
|
||||
min-height: 1.5em;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
@media (width >= 48rem) {
|
||||
.consent-text {
|
||||
max-height: 20rem;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
import { useEffect, useId, useRef, useState, type FormEvent } from "react";
|
||||
import {
|
||||
useGetConsentText,
|
||||
useRegisterAccount,
|
||||
} from "../../../shared/api/endpoints/identity/identity";
|
||||
import type { Account } from "../../../shared/api/schemas";
|
||||
import { Button, ErrorState, LoadingState, TextLink } from "../../../shared/ui";
|
||||
import { paths } from "../../../shared/config";
|
||||
import { validateRegistration } from "../model/validation";
|
||||
import styles from "./register-form.module.css";
|
||||
|
||||
type Scenario = Account["scenario"];
|
||||
|
||||
export type RegistrationDraft = {
|
||||
email: string;
|
||||
scenario: Scenario | "";
|
||||
};
|
||||
|
||||
type RegisterFormProps = {
|
||||
initialEmail?: string;
|
||||
initialScenario?: Scenario | "";
|
||||
onDraftChange?: (draft: RegistrationDraft) => void;
|
||||
onAccepted: (draft: RegistrationDraft) => void;
|
||||
};
|
||||
|
||||
type FieldErrors = {
|
||||
email?: string;
|
||||
password?: string;
|
||||
scenario?: string;
|
||||
consent?: string;
|
||||
};
|
||||
|
||||
function createIdempotencyKey(): string {
|
||||
return window.crypto.randomUUID();
|
||||
}
|
||||
|
||||
function registrationError(error: unknown): {
|
||||
message: string;
|
||||
refreshConsent: boolean;
|
||||
clearIdempotencyKey: boolean;
|
||||
} {
|
||||
if (!(error instanceof Error) || !("code" in error)) {
|
||||
return {
|
||||
message: "Не удалось отправить запрос. Повторите попытку.",
|
||||
refreshConsent: false,
|
||||
clearIdempotencyKey: false,
|
||||
};
|
||||
}
|
||||
const code = String(error.code);
|
||||
if (code === "validation_failed" && "fieldErrors" in error) {
|
||||
const fields = error.fieldErrors as readonly { pointer?: string }[];
|
||||
if (fields.some((field) => field.pointer === "/consent_c1/text_version")) {
|
||||
return {
|
||||
message: "Текст согласия обновился. Прочитайте новую версию и подтвердите ее.",
|
||||
refreshConsent: true,
|
||||
clearIdempotencyKey: true,
|
||||
};
|
||||
}
|
||||
if (fields.some((field) => field.pointer === "/password")) {
|
||||
return {
|
||||
message: "Этот пароль не подходит. Выберите другой пароль и повторите попытку.",
|
||||
refreshConsent: false,
|
||||
clearIdempotencyKey: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
if (code === "rate_limited") {
|
||||
return {
|
||||
message: "Слишком много запросов. Подождите и попробуйте снова.",
|
||||
refreshConsent: false,
|
||||
clearIdempotencyKey: false,
|
||||
};
|
||||
}
|
||||
if (code === "idempotency_key_reused") {
|
||||
return {
|
||||
message: "Не удалось повторить запрос. Отправьте форму еще раз.",
|
||||
refreshConsent: false,
|
||||
clearIdempotencyKey: true,
|
||||
};
|
||||
}
|
||||
if (code === "csrf_check_failed") {
|
||||
return {
|
||||
message: "Не удалось проверить источник запроса. Обновите страницу и попробуйте снова.",
|
||||
refreshConsent: false,
|
||||
clearIdempotencyKey: false,
|
||||
};
|
||||
}
|
||||
return {
|
||||
message: "Не удалось отправить запрос. Повторите попытку.",
|
||||
refreshConsent: false,
|
||||
clearIdempotencyKey: false,
|
||||
};
|
||||
}
|
||||
|
||||
function errorId(id: string, name: keyof FieldErrors): string {
|
||||
return `${id}-${name}-error`;
|
||||
}
|
||||
|
||||
export function RegisterForm({
|
||||
initialEmail = "",
|
||||
initialScenario = "",
|
||||
onDraftChange,
|
||||
onAccepted,
|
||||
}: RegisterFormProps) {
|
||||
const id = useId();
|
||||
const consent = useGetConsentText("c1");
|
||||
const registration = useRegisterAccount({ mutation: { gcTime: 0 } });
|
||||
const idempotencyKey = useRef<string | null>(null);
|
||||
const [email, setEmail] = useState(initialEmail);
|
||||
const [password, setPassword] = useState("");
|
||||
const [scenario, setScenario] = useState<Scenario | "">(initialScenario);
|
||||
const [acceptedVersion, setAcceptedVersion] = useState<string | null>(null);
|
||||
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const previousConsentVersion = useRef<string | undefined>(undefined);
|
||||
const currentConsentVersion = consent.data?.text_version;
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
currentConsentVersion &&
|
||||
previousConsentVersion.current &&
|
||||
currentConsentVersion !== previousConsentVersion.current
|
||||
) {
|
||||
idempotencyKey.current = null;
|
||||
setAcceptedVersion(null);
|
||||
setFormError("Текст согласия обновился. Прочитайте новую версию и подтвердите ее.");
|
||||
}
|
||||
if (currentConsentVersion) previousConsentVersion.current = currentConsentVersion;
|
||||
}, [currentConsentVersion]);
|
||||
|
||||
function changed() {
|
||||
idempotencyKey.current = null;
|
||||
setFieldErrors({});
|
||||
setFormError(null);
|
||||
}
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (registration.isPending || !consent.data || consent.isError) return;
|
||||
|
||||
const errors = validateRegistration({
|
||||
email,
|
||||
password,
|
||||
scenario,
|
||||
acceptedConsent: Boolean(consent.data && acceptedVersion === consent.data.text_version),
|
||||
});
|
||||
setFieldErrors(errors);
|
||||
setFormError(null);
|
||||
if (Object.keys(errors).length > 0 || !scenario) return;
|
||||
|
||||
const body = {
|
||||
email,
|
||||
password,
|
||||
scenario,
|
||||
consent_c1: { text_version: consent.data.text_version, accepted: true as const },
|
||||
};
|
||||
idempotencyKey.current ??= createIdempotencyKey();
|
||||
|
||||
try {
|
||||
await registration.mutateAsync({
|
||||
data: body,
|
||||
headers: { "Idempotency-Key": idempotencyKey.current },
|
||||
});
|
||||
setPassword("");
|
||||
onAccepted({ email, scenario });
|
||||
} catch (error: unknown) {
|
||||
const result = registrationError(error);
|
||||
setFormError(result.message);
|
||||
if (result.clearIdempotencyKey) idempotencyKey.current = null;
|
||||
if (result.refreshConsent) {
|
||||
setAcceptedVersion(null);
|
||||
await consent.refetch();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form className={styles.form} onSubmit={(event) => void submit(event)} noValidate>
|
||||
{consent.isPending ? <LoadingState label="Загружаем текст согласия..." /> : null}
|
||||
{consent.isError ? (
|
||||
<ErrorState
|
||||
error={consent.error}
|
||||
isRetrying={consent.isRefetching}
|
||||
onRetry={() => void consent.refetch()}
|
||||
title="Не удалось загрузить текст согласия"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<div className={styles.field}>
|
||||
<label className={styles.label} htmlFor={`${id}-email`}>
|
||||
Электронная почта
|
||||
</label>
|
||||
<input
|
||||
className={styles.input}
|
||||
id={`${id}-email`}
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
maxLength={254}
|
||||
value={email}
|
||||
disabled={registration.isPending}
|
||||
aria-invalid={Boolean(fieldErrors.email)}
|
||||
aria-describedby={fieldErrors.email ? errorId(id, "email") : undefined}
|
||||
onChange={(event) => {
|
||||
changed();
|
||||
const nextEmail = event.currentTarget.value;
|
||||
setEmail(nextEmail);
|
||||
onDraftChange?.({ email: nextEmail, scenario });
|
||||
}}
|
||||
/>
|
||||
{fieldErrors.email ? (
|
||||
<p className={styles.error} id={errorId(id, "email")}>
|
||||
{fieldErrors.email}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className={styles.field}>
|
||||
<label className={styles.label} htmlFor={`${id}-password`}>
|
||||
Пароль
|
||||
</label>
|
||||
<input
|
||||
className={styles.input}
|
||||
id={`${id}-password`}
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
required
|
||||
maxLength={512}
|
||||
value={password}
|
||||
disabled={registration.isPending}
|
||||
aria-invalid={Boolean(fieldErrors.password)}
|
||||
aria-describedby={`${id}-password-hint${fieldErrors.password ? ` ${errorId(id, "password")}` : ""}`}
|
||||
onChange={(event) => {
|
||||
changed();
|
||||
setPassword(event.currentTarget.value);
|
||||
}}
|
||||
/>
|
||||
<p className={styles.hint} id={`${id}-password-hint`}>
|
||||
От 15 до 128 символов после нормализации. Допустима фраза из нескольких слов.
|
||||
</p>
|
||||
{fieldErrors.password ? (
|
||||
<p className={styles.error} id={errorId(id, "password")}>
|
||||
{fieldErrors.password}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<fieldset
|
||||
className={styles.choices}
|
||||
aria-describedby={fieldErrors.scenario ? errorId(id, "scenario") : undefined}
|
||||
>
|
||||
<legend>Сценарий</legend>
|
||||
{(
|
||||
[
|
||||
["candidate", "Кандидат", "Ищу работу и хочу подтвердить навыки."],
|
||||
["employer", "Работодатель", "Представляю компанию и ищу кандидатов."],
|
||||
] as const
|
||||
).map(([value, label, description]) => (
|
||||
<label className={styles.choice} key={value} htmlFor={`${id}-${value}`}>
|
||||
<input
|
||||
id={`${id}-${value}`}
|
||||
name="scenario"
|
||||
type="radio"
|
||||
value={value}
|
||||
checked={scenario === value}
|
||||
required
|
||||
disabled={registration.isPending}
|
||||
onChange={() => {
|
||||
changed();
|
||||
setScenario(value);
|
||||
onDraftChange?.({ email, scenario: value });
|
||||
}}
|
||||
/>
|
||||
<span className={styles["choice-body"]}>
|
||||
<span className={styles.label}>{label}</span>
|
||||
<span className={styles["choice-description"]}>{description}</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
{fieldErrors.scenario ? (
|
||||
<p className={styles.error} id={errorId(id, "scenario")}>
|
||||
{fieldErrors.scenario}
|
||||
</p>
|
||||
) : null}
|
||||
</fieldset>
|
||||
|
||||
{consent.data ? (
|
||||
<section className={styles.consent} aria-labelledby={`${id}-consent-title`}>
|
||||
<h2 className={styles["consent-title"]} id={`${id}-consent-title`}>
|
||||
Согласие C1 на обработку персональных данных
|
||||
</h2>
|
||||
<p className={styles.hint}>Версия текста: {consent.data.text_version}</p>
|
||||
<div
|
||||
className={styles["consent-text"]}
|
||||
role="region"
|
||||
tabIndex={0}
|
||||
aria-label="Полный текст согласия C1"
|
||||
>
|
||||
{consent.data.text}
|
||||
</div>
|
||||
<label className={styles["consent-choice"]} htmlFor={`${id}-consent`}>
|
||||
<input
|
||||
id={`${id}-consent`}
|
||||
name="consent_c1"
|
||||
type="checkbox"
|
||||
checked={Boolean(currentConsentVersion && acceptedVersion === currentConsentVersion)}
|
||||
required
|
||||
disabled={registration.isPending}
|
||||
aria-invalid={Boolean(
|
||||
fieldErrors.consent ||
|
||||
(acceptedVersion && acceptedVersion !== currentConsentVersion),
|
||||
)}
|
||||
aria-describedby={
|
||||
fieldErrors.consent
|
||||
? errorId(id, "consent")
|
||||
: acceptedVersion && acceptedVersion !== currentConsentVersion
|
||||
? `${id}-consent-version-error`
|
||||
: undefined
|
||||
}
|
||||
onChange={(event) => {
|
||||
changed();
|
||||
setAcceptedVersion(
|
||||
event.currentTarget.checked ? (currentConsentVersion ?? null) : null,
|
||||
);
|
||||
idempotencyKey.current = null;
|
||||
}}
|
||||
/>
|
||||
<span>Я прочитал(а) текст согласия C1 и принимаю его.</span>
|
||||
</label>
|
||||
{acceptedVersion && acceptedVersion !== currentConsentVersion ? (
|
||||
<p className={styles.error} id={`${id}-consent-version-error`}>
|
||||
Текст согласия изменился. Прочитайте новую версию и подтвердите ее.
|
||||
</p>
|
||||
) : null}
|
||||
{fieldErrors.consent ? (
|
||||
<p className={styles.error} id={errorId(id, "consent")}>
|
||||
{fieldErrors.consent}
|
||||
</p>
|
||||
) : null}
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{formError ? (
|
||||
<p className={styles.alert} role="alert">
|
||||
{formError}
|
||||
</p>
|
||||
) : null}
|
||||
{consent.isError && consent.error ? (
|
||||
<p className={styles.hint}>Без опубликованного текста C1 отправить регистрацию нельзя.</p>
|
||||
) : null}
|
||||
|
||||
<div className={styles.actions}>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={!consent.data || consent.isError}
|
||||
isBusy={registration.isPending}
|
||||
>
|
||||
{registration.isPending ? "Отправляем..." : "Создать аккаунт"}
|
||||
</Button>
|
||||
<TextLink to={paths.login}>Уже есть аккаунт? Войти</TextLink>
|
||||
</div>
|
||||
<p className={styles.status} role="status" aria-live="polite">
|
||||
{registration.isPending ? "Отправляем запрос на регистрацию..." : ""}
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { ResendVerificationForm } from "./ui/resend-verification-form";
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
.form {
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.label {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.input {
|
||||
width: 100%;
|
||||
min-height: 2.75rem;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.input[aria-invalid="true"] {
|
||||
border-color: var(--color-danger);
|
||||
}
|
||||
|
||||
.error,
|
||||
.message {
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.error {
|
||||
color: var(--color-danger);
|
||||
}
|
||||
|
||||
.message {
|
||||
min-height: 1.5em;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
align-items: center;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { useId, useState, type FormEvent } from "react";
|
||||
import { useResendEmailVerification } from "../../../shared/api/endpoints/identity/identity";
|
||||
import { EmailAddress } from "../../../shared/api/schemas";
|
||||
import { Button } from "../../../shared/ui";
|
||||
import styles from "./resend-verification-form.module.css";
|
||||
|
||||
type ResendVerificationFormProps = {
|
||||
initialEmail?: string;
|
||||
};
|
||||
|
||||
export function ResendVerificationForm({ initialEmail = "" }: ResendVerificationFormProps) {
|
||||
const id = useId();
|
||||
const resend = useResendEmailVerification({ mutation: { gcTime: 0 } });
|
||||
const [email, setEmail] = useState(initialEmail);
|
||||
const [fieldError, setFieldError] = useState<string | null>(null);
|
||||
const [message, setMessage] = useState("");
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (resend.isPending) return;
|
||||
|
||||
if (!EmailAddress.safeParse(email).success) {
|
||||
setFieldError("Введите корректный адрес электронной почты.");
|
||||
setMessage("");
|
||||
return;
|
||||
}
|
||||
|
||||
setFieldError(null);
|
||||
setMessage("");
|
||||
try {
|
||||
await resend.mutateAsync({ data: { email } });
|
||||
setMessage(
|
||||
"Запрос принят. Если для этого адреса доступна повторная отправка, письмо будет отправлено.",
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
const code = error instanceof Error && "code" in error ? String(error.code) : "";
|
||||
if (code === "rate_limited") {
|
||||
setMessage("Слишком много запросов. Подождите и повторите попытку.");
|
||||
} else if (code === "csrf_check_failed") {
|
||||
setMessage("Не удалось проверить источник запроса. Обновите страницу и повторите попытку.");
|
||||
} else {
|
||||
setMessage("Не удалось отправить запрос. Повторите попытку.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form className={styles.form} onSubmit={(event) => void submit(event)} noValidate>
|
||||
<div className={styles.field}>
|
||||
<label className={styles.label} htmlFor={`${id}-email`}>
|
||||
Адрес для письма
|
||||
</label>
|
||||
<input
|
||||
className={styles.input}
|
||||
id={`${id}-email`}
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
maxLength={254}
|
||||
value={email}
|
||||
disabled={resend.isPending}
|
||||
aria-invalid={Boolean(fieldError)}
|
||||
aria-describedby={fieldError ? `${id}-email-error` : undefined}
|
||||
onChange={(event) => {
|
||||
setEmail(event.currentTarget.value);
|
||||
setFieldError(null);
|
||||
setMessage("");
|
||||
}}
|
||||
/>
|
||||
{fieldError ? (
|
||||
<p className={styles.error} id={`${id}-email-error`}>
|
||||
{fieldError}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className={styles.actions}>
|
||||
<Button type="submit" variant="secondary" isBusy={resend.isPending}>
|
||||
{resend.isPending ? "Отправляем..." : "Отправить письмо повторно"}
|
||||
</Button>
|
||||
</div>
|
||||
<p className={styles.message} role="status" aria-live="polite">
|
||||
{resend.isPending ? "Отправляем запрос..." : message}
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { SignInForm } from "./ui/sign-in-form";
|
||||
@@ -0,0 +1,38 @@
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
|
||||
import { establishSession } from "./establish-session";
|
||||
|
||||
describe("establishSession", () => {
|
||||
it("removes cached account data before keeping the new session in memory", () => {
|
||||
const queryClient = new QueryClient();
|
||||
const previousProfileKey = ["/api/v1/candidate/profile"] as const;
|
||||
const nextSession = {
|
||||
account: {
|
||||
id: "22222222-2222-4222-8222-222222222222",
|
||||
email: "new@example.test",
|
||||
email_verified: true,
|
||||
scenario: "employer",
|
||||
onboarding_step: "employer_company",
|
||||
created_at: "2026-10-07T12:00:00Z",
|
||||
},
|
||||
csrf_token: "B".repeat(43),
|
||||
} as const;
|
||||
|
||||
queryClient.setQueryData(previousProfileKey, {
|
||||
accountId: "11111111-1111-4111-8111-111111111111",
|
||||
privateNotes: ["previous account data"],
|
||||
});
|
||||
queryClient.setQueryData(getGetCurrentSessionQueryKey(), {
|
||||
...nextSession,
|
||||
account: { ...nextSession.account, id: "11111111-1111-4111-8111-111111111111" },
|
||||
csrf_token: "A".repeat(43),
|
||||
});
|
||||
|
||||
establishSession(queryClient, nextSession);
|
||||
|
||||
expect(queryClient.getQueryData(previousProfileKey)).toBeUndefined();
|
||||
expect(queryClient.getQueryData(getGetCurrentSessionQueryKey())).toEqual(nextSession);
|
||||
expect(queryClient.getQueryCache().getAll()).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
import { getGetCurrentSessionQueryKey } from "../../../shared/api/endpoints/identity/identity";
|
||||
import type { Session } from "../../../shared/api/schemas";
|
||||
|
||||
/** Drop data from any previous account before caching the new in-memory session. */
|
||||
export function establishSession(queryClient: QueryClient, session: Session): void {
|
||||
queryClient.clear();
|
||||
queryClient.setQueryData(getGetCurrentSessionQueryKey(), session);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
.form {
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.label {
|
||||
font-weight: var(--font-weight-bold);
|
||||
}
|
||||
|
||||
.input {
|
||||
width: 100%;
|
||||
min-height: 2.75rem;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border: var(--line-thin) solid var(--color-border-strong);
|
||||
border-radius: var(--radius-s);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.input[aria-invalid="true"] {
|
||||
border-color: var(--color-danger);
|
||||
}
|
||||
|
||||
.error,
|
||||
.hint {
|
||||
font-size: var(--font-size-s);
|
||||
}
|
||||
|
||||
.error,
|
||||
.alert {
|
||||
color: var(--color-danger);
|
||||
}
|
||||
|
||||
.alert {
|
||||
padding: var(--space-3);
|
||||
border-left: var(--line-strong) solid var(--color-danger);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
|
||||
.hint {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-3);
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.status {
|
||||
min-height: 1.5em;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useId, useState, type FormEvent } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { ApiRequestError } from "../../../shared/api";
|
||||
import { useLogin } from "../../../shared/api/endpoints/identity/identity";
|
||||
import { EmailAddress } from "../../../shared/api/schemas";
|
||||
import { paths } from "../../../shared/config";
|
||||
import { getOnboardingDestination } from "../../../entities/session";
|
||||
import { Button, TextLink } from "../../../shared/ui";
|
||||
import { establishSession } from "../model/establish-session";
|
||||
import styles from "./sign-in-form.module.css";
|
||||
|
||||
type SignInFormProps = {
|
||||
onUnverified: (email: string) => void;
|
||||
onSignedIn: () => void;
|
||||
};
|
||||
|
||||
export function SignInForm({ onUnverified, onSignedIn }: SignInFormProps) {
|
||||
const id = useId();
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const login = useLogin({ mutation: { gcTime: 0 } });
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [fieldError, setFieldError] = useState<{ email?: string; password?: string }>({});
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (login.isPending) return;
|
||||
|
||||
const errors: typeof fieldError = {};
|
||||
if (!EmailAddress.safeParse(email).success) {
|
||||
errors.email = "Введите корректный адрес электронной почты.";
|
||||
}
|
||||
const passwordLength = Array.from(password.normalize("NFKC")).length;
|
||||
if (passwordLength < 1 || passwordLength > 128) {
|
||||
errors.password = "Введите пароль длиной не более 128 символов.";
|
||||
}
|
||||
setFieldError(errors);
|
||||
setFormError(null);
|
||||
if (Object.keys(errors).length > 0) return;
|
||||
|
||||
try {
|
||||
const session = await login.mutateAsync({ data: { email, password } });
|
||||
establishSession(queryClient, session);
|
||||
setPassword("");
|
||||
onSignedIn();
|
||||
await navigate(getOnboardingDestination(session.account), { replace: true });
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof ApiRequestError && error.code === "email_not_verified") {
|
||||
onUnverified(email);
|
||||
setFormError("Почта не подтверждена. Запросите новое письмо и перейдите по ссылке.");
|
||||
} else if (error instanceof ApiRequestError && error.code === "invalid_credentials") {
|
||||
setFormError("Не удалось войти. Проверьте адрес и пароль.");
|
||||
} else if (error instanceof ApiRequestError && error.code === "rate_limited") {
|
||||
setFormError("Слишком много попыток. Подождите и попробуйте снова.");
|
||||
} else if (error instanceof ApiRequestError && error.code === "csrf_check_failed") {
|
||||
setFormError(
|
||||
"Не удалось проверить источник запроса. Обновите страницу и попробуйте снова.",
|
||||
);
|
||||
} else {
|
||||
setFormError("Не удалось выполнить вход. Проверьте соединение и повторите попытку.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function changed() {
|
||||
setFieldError({});
|
||||
setFormError(null);
|
||||
onUnverified("");
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.form}>
|
||||
<form onSubmit={(event) => void submit(event)} noValidate>
|
||||
<div className={styles.form}>
|
||||
<div className={styles.field}>
|
||||
<label className={styles.label} htmlFor={`${id}-email`}>
|
||||
Электронная почта
|
||||
</label>
|
||||
<input
|
||||
className={styles.input}
|
||||
id={`${id}-email`}
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="username"
|
||||
required
|
||||
maxLength={254}
|
||||
value={email}
|
||||
disabled={login.isPending}
|
||||
aria-invalid={Boolean(fieldError.email)}
|
||||
aria-describedby={fieldError.email ? `${id}-email-error` : undefined}
|
||||
onChange={(event) => {
|
||||
changed();
|
||||
setEmail(event.currentTarget.value);
|
||||
}}
|
||||
/>
|
||||
{fieldError.email ? (
|
||||
<p className={styles.error} id={`${id}-email-error`}>
|
||||
{fieldError.email}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className={styles.field}>
|
||||
<label className={styles.label} htmlFor={`${id}-password`}>
|
||||
Пароль
|
||||
</label>
|
||||
<input
|
||||
className={styles.input}
|
||||
id={`${id}-password`}
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
maxLength={512}
|
||||
value={password}
|
||||
disabled={login.isPending}
|
||||
aria-invalid={Boolean(fieldError.password)}
|
||||
aria-describedby={fieldError.password ? `${id}-password-error` : undefined}
|
||||
onChange={(event) => {
|
||||
changed();
|
||||
setPassword(event.currentTarget.value);
|
||||
}}
|
||||
/>
|
||||
{fieldError.password ? (
|
||||
<p className={styles.error} id={`${id}-password-error`}>
|
||||
{fieldError.password}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{formError ? (
|
||||
<p className={styles.alert} role="alert">
|
||||
{formError}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className={styles.actions}>
|
||||
<Button type="submit" isBusy={login.isPending}>
|
||||
{login.isPending ? "Входим..." : "Войти"}
|
||||
</Button>
|
||||
<TextLink to={paths.register}>Создать аккаунт</TextLink>
|
||||
</div>
|
||||
<p className={styles.status} role="status" aria-live="polite">
|
||||
{login.isPending ? "Проверяем учетные данные..." : ""}
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user