fix: harden editorial registration flow

This commit is contained in:
Leon Tonhäuser committed 2026-08-09 21:04:50 +02:00
1 parent 9b22752ef2
commit a8d4e54ffb
8 files changed
+398 -62

No files matched your search

+5 -2
View File
@@ -3,7 +3,10 @@ import { redirect } from "next/navigation";
import { env } from "@/config/env"; import { env } from "@/config/env";
import { registerEditorial } from "@/modules/auth/auth"; import { registerEditorial } from "@/modules/auth/auth";
import { RegistrationValidationError } from "@/modules/auth/registration"; import {
CURRENT_TERMS_VERSION,
RegistrationValidationError,
} from "@/modules/auth/registration";
import { import {
RegistrationForm, RegistrationForm,
type RegistrationFormState, type RegistrationFormState,
@@ -57,7 +60,7 @@ async function registerAction(
countryCode: text(formData, "countryCode"), countryCode: text(formData, "countryCode"),
}, },
actsForBusiness: formData.has("actsForBusiness"), actsForBusiness: formData.has("actsForBusiness"),
termsVersion: formData.has("termsAccepted") ? text(formData, "termsVersion") : "", termsVersion: formData.has("termsAccepted") ? CURRENT_TERMS_VERSION : "",
privacyAcknowledged: formData.has("privacyAcknowledged"), privacyAcknowledged: formData.has("privacyAcknowledged"),
}); });
} catch (error) { } catch (error) {
+20 -1
View File
@@ -1,5 +1,24 @@
import { toNextJsHandler } from "better-auth/next-js"; import { toNextJsHandler } from "better-auth/next-js";
import { NextResponse } from "next/server";
import { auth } from "@/modules/auth/auth"; import { auth } from "@/modules/auth/auth";
export const { GET, POST } = toNextJsHandler(auth); const handlers = toNextJsHandler(auth);
export const GET = handlers.GET;
export async function POST(
request: Request,
{ params }: { params: Promise<{ all: string[] }> },
): Promise<Response> {
const { all } = await params;
if (all.join("/") === "sign-up/email") {
return NextResponse.json(
{ message: "Bitte verwenden Sie die Registrierung des Redaktionsportals." },
{ status: 403 },
);
}
return handlers.POST(request);
}
+46 -4
View File
@@ -1,9 +1,50 @@
import { expect, test } from "vitest"; import { memoryAdapter } from "better-auth/adapters/memory";
import { expect, test, vi } from "vitest";
import { auth } from "./auth"; import { POST } from "@/app/api/auth/[...all]/route";
test("rejects direct Better Auth sign-up requests that bypass B2B registration", async () => { import { createPortalAuth } from "./auth";
const response = await auth.handler( import { CURRENT_TERMS_VERSION } from "./registration";
test("allows the trusted registration service ingress while rejecting public direct sign-up", async () => {
const registrationRepository = {
createEditorial: vi.fn(),
markPendingApproval: vi.fn(),
removeUnverifiedAuthIdentity: vi.fn(),
recordRegistrationCompensationFailure: vi.fn(),
recordVerificationInconsistency: vi.fn(),
canCreateSession: vi.fn().mockResolvedValue(false),
};
const { registrationService } = createPortalAuth({
database: memoryAdapter({ user: [], account: [], session: [], verification: [] }),
mailerService: {
sendPasswordReset: vi.fn(),
sendVerification: vi.fn(),
},
registrationRepository,
});
await expect(
registrationService.register({
companyName: "Registration GmbH",
contactName: "Registration Service",
email: "registration@example.com",
password: "sicheres-passwort-123",
billingAddress: {
addressLine1: "Presseweg 1",
postalCode: "10115",
city: "Berlin",
countryCode: "DE",
},
actsForBusiness: true,
termsVersion: CURRENT_TERMS_VERSION,
privacyAcknowledged: true,
}),
).resolves.toEqual({ status: "pending_email" });
expect(registrationRepository.createEditorial).toHaveBeenCalledTimes(1);
const response = await POST(
new Request("http://localhost:3000/api/auth/sign-up/email", { new Request("http://localhost:3000/api/auth/sign-up/email", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
@@ -13,6 +54,7 @@ test("rejects direct Better Auth sign-up requests that bypass B2B registration",
password: "sicheres-passwort-123", password: "sicheres-passwort-123",
}), }),
}), }),
{ params: Promise.resolve({ all: ["sign-up", "email"] }) },
); );
expect(response.status).toBe(403); expect(response.status).toBe(403);
+41 -26
View File
@@ -1,8 +1,7 @@
import "server-only"; import "server-only";
import { drizzleAdapter } from "@better-auth/drizzle-adapter"; import { drizzleAdapter } from "@better-auth/drizzle-adapter";
import { betterAuth } from "better-auth"; import { betterAuth, type BetterAuthOptions } from "better-auth";
import { APIError, createAuthMiddleware } from "better-auth/api";
import { env } from "@/config/env"; import { env } from "@/config/env";
import { db } from "@/db/client"; import { db } from "@/db/client";
@@ -15,29 +14,21 @@ import {
type RegistrationInput, type RegistrationInput,
} from "./registration"; } from "./registration";
const registrationRepository = createEditorialRegistrationRepository(db); export function createPortalAuth({
database,
mailerService,
registrationRepository,
}: {
database: NonNullable<BetterAuthOptions["database"]>;
mailerService: Pick<typeof mailer, "sendPasswordReset" | "sendVerification">;
registrationRepository: ReturnType<typeof createEditorialRegistrationRepository>;
}) {
let registrationService: ReturnType<typeof createRegistrationService> | undefined;
export const auth = betterAuth({ const auth = betterAuth({
baseURL: env.BETTER_AUTH_URL, baseURL: env.BETTER_AUTH_URL,
secret: env.BETTER_AUTH_SECRET, secret: env.BETTER_AUTH_SECRET,
database: drizzleAdapter(db, { database,
provider: "pg",
schema: {
user: users,
account: accounts,
session: sessions,
verification: verifications,
},
}),
hooks: {
before: createAuthMiddleware(async (context) => {
if (context.path === "/sign-up/email") {
throw new APIError("FORBIDDEN", {
message: "Bitte verwenden Sie die Registrierung des Redaktionsportals.",
});
}
}),
},
emailAndPassword: { emailAndPassword: {
enabled: true, enabled: true,
requireEmailVerification: true, requireEmailVerification: true,
@@ -45,7 +36,7 @@ export const auth = betterAuth({
resetPasswordTokenExpiresIn: 60 * 60, resetPasswordTokenExpiresIn: 60 * 60,
revokeSessionsOnPasswordReset: true, revokeSessionsOnPasswordReset: true,
async sendResetPassword({ user, url }) { async sendResetPassword({ user, url }) {
await mailer.sendPasswordReset({ to: user.email, resetUrl: url }); await mailerService.sendPasswordReset({ to: user.email, resetUrl: url });
}, },
}, },
emailVerification: { emailVerification: {
@@ -53,9 +44,12 @@ export const auth = betterAuth({
autoSignInAfterVerification: false, autoSignInAfterVerification: false,
expiresIn: 60 * 60, expiresIn: 60 * 60,
async sendVerificationEmail({ user, url }) { async sendVerificationEmail({ user, url }) {
await mailer.sendVerification({ to: user.email, verificationUrl: url }); await mailerService.sendVerification({ to: user.email, verificationUrl: url });
}, },
async afterEmailVerification(user) { async afterEmailVerification(user) {
if (!registrationService) {
throw new Error("Registration service is unavailable.");
}
await registrationService.onEmailVerified(user.id); await registrationService.onEmailVerified(user.id);
}, },
}, },
@@ -68,9 +62,9 @@ export const auth = betterAuth({
}, },
}, },
}, },
}); });
export const registrationService = createRegistrationService({ registrationService = createRegistrationService({
auth: { auth: {
async signUpEmail({ email, name, password }) { async signUpEmail({ email, name, password }) {
return auth.api.signUpEmail({ body: { email, name, password } }); return auth.api.signUpEmail({ body: { email, name, password } });
@@ -83,8 +77,29 @@ export const registrationService = createRegistrationService({
}, },
repo: registrationRepository, repo: registrationRepository,
audit: registrationRepository, audit: registrationRepository,
});
return { auth, registrationService };
}
const registrationRepository = createEditorialRegistrationRepository(db);
const portalAuth = createPortalAuth({
database: drizzleAdapter(db, {
provider: "pg",
schema: {
user: users,
account: accounts,
session: sessions,
verification: verifications,
},
}),
mailerService: mailer,
registrationRepository,
}); });
export const auth = portalAuth.auth;
export const registrationService = portalAuth.registrationService;
export function registerEditorial(input: RegistrationInput): Promise<{ status: "pending_email" }> { export function registerEditorial(input: RegistrationInput): Promise<{ status: "pending_email" }> {
return registrationService.register(input); return registrationService.register(input);
} }
+1
View File
@@ -38,4 +38,5 @@ test("registration presents separate B2B, terms, and privacy acknowledgements",
"href", "href",
"https://example.com/datenschutz", "https://example.com/datenschutz",
); );
expect(document.querySelector('input[name="termsVersion"]')).toBeNull();
}); });
+22 -2
View File
@@ -6,7 +6,20 @@ import { authClient } from "./client";
export type RegistrationFormState = { export type RegistrationFormState = {
errors?: Partial< errors?: Partial<
Record<"actsForBusiness" | "termsVersion" | "privacyAcknowledged", string> Record<
| "companyName"
| "contactName"
| "email"
| "password"
| "addressLine1"
| "postalCode"
| "city"
| "countryCode"
| "actsForBusiness"
| "termsVersion"
| "privacyAcknowledged",
string
>
>; >;
}; };
@@ -34,28 +47,32 @@ export function RegistrationForm({
return ( return (
<form action={formAction} className="account-form"> <form action={formAction} className="account-form">
<input name="termsVersion" type="hidden" value="2026-08" />
<div className="form-grid"> <div className="form-grid">
<label> <label>
Redaktion oder Unternehmen Redaktion oder Unternehmen
<input autoComplete="organization" name="companyName" required /> <input autoComplete="organization" name="companyName" required />
</label> </label>
<FieldError message={state.errors?.companyName} />
<label> <label>
Ansprechpartner:in Ansprechpartner:in
<input autoComplete="name" name="contactName" required /> <input autoComplete="name" name="contactName" required />
</label> </label>
<FieldError message={state.errors?.contactName} />
<label> <label>
E-Mail-Adresse E-Mail-Adresse
<input autoComplete="email" name="email" required type="email" /> <input autoComplete="email" name="email" required type="email" />
</label> </label>
<FieldError message={state.errors?.email} />
<label> <label>
Passwort Passwort
<input autoComplete="new-password" minLength={8} name="password" required type="password" /> <input autoComplete="new-password" minLength={8} name="password" required type="password" />
</label> </label>
<FieldError message={state.errors?.password} />
<label> <label>
Straße und Hausnummer Straße und Hausnummer
<input autoComplete="address-line1" name="addressLine1" required /> <input autoComplete="address-line1" name="addressLine1" required />
</label> </label>
<FieldError message={state.errors?.addressLine1} />
<label> <label>
Adresszusatz Adresszusatz
<input autoComplete="address-line2" name="addressLine2" /> <input autoComplete="address-line2" name="addressLine2" />
@@ -64,10 +81,12 @@ export function RegistrationForm({
Postleitzahl Postleitzahl
<input autoComplete="postal-code" name="postalCode" required /> <input autoComplete="postal-code" name="postalCode" required />
</label> </label>
<FieldError message={state.errors?.postalCode} />
<label> <label>
Ort Ort
<input autoComplete="address-level2" name="city" required /> <input autoComplete="address-level2" name="city" required />
</label> </label>
<FieldError message={state.errors?.city} />
<label> <label>
Land (ISO-Code) Land (ISO-Code)
<input <input
@@ -78,6 +97,7 @@ export function RegistrationForm({
required required
/> />
</label> </label>
<FieldError message={state.errors?.countryCode} />
</div> </div>
<fieldset className="acknowledgements"> <fieldset className="acknowledgements">
+91 -3
View File
@@ -1,6 +1,7 @@
import { describe, expect, test, vi } from "vitest"; import { describe, expect, test, vi } from "vitest";
import { import {
CURRENT_TERMS_VERSION,
RegistrationValidationError, RegistrationValidationError,
createRegistrationService, createRegistrationService,
type RegistrationInput, type RegistrationInput,
@@ -20,10 +21,14 @@ const validRegistration: RegistrationInput = {
countryCode: "DE", countryCode: "DE",
}, },
actsForBusiness: true, actsForBusiness: true,
termsVersion: "2026-08", termsVersion: CURRENT_TERMS_VERSION,
privacyAcknowledged: true, privacyAcknowledged: true,
}; };
type RegistrationChange = Partial<Omit<RegistrationInput, "billingAddress">> & {
billingAddress?: RegistrationInput["billingAddress"];
};
function createService() { function createService() {
const auth = { const auth = {
signUpEmail: vi.fn().mockResolvedValue({ user: { id: "user-1" } }), signUpEmail: vi.fn().mockResolvedValue({ user: { id: "user-1" } }),
@@ -32,8 +37,10 @@ function createService() {
const repo = { const repo = {
createEditorial: vi.fn().mockResolvedValue(undefined), createEditorial: vi.fn().mockResolvedValue(undefined),
markPendingApproval: vi.fn().mockResolvedValue(true), markPendingApproval: vi.fn().mockResolvedValue(true),
removeUnverifiedAuthIdentity: vi.fn().mockResolvedValue(true),
}; };
const audit = { const audit = {
recordRegistrationCompensationFailure: vi.fn().mockResolvedValue(undefined),
recordVerificationInconsistency: vi.fn().mockResolvedValue(undefined), recordVerificationInconsistency: vi.fn().mockResolvedValue(undefined),
}; };
const now = new Date("2026-08-09T10:00:00.000Z"); const now = new Date("2026-08-09T10:00:00.000Z");
@@ -63,7 +70,7 @@ describe("editorial registration", () => {
contactName: "Mara Muster", contactName: "Mara Muster",
loginEmail: "mara.muster@example.com", loginEmail: "mara.muster@example.com",
status: "pending_email", status: "pending_email",
acceptedTermsVersion: "2026-08", acceptedTermsVersion: CURRENT_TERMS_VERSION,
acceptedTermsAt: new Date("2026-08-09T10:00:00.000Z"), acceptedTermsAt: new Date("2026-08-09T10:00:00.000Z"),
privacyAcknowledgedAt: new Date("2026-08-09T10:00:00.000Z"), privacyAcknowledgedAt: new Date("2026-08-09T10:00:00.000Z"),
billingAddress: { billingAddress: {
@@ -105,7 +112,7 @@ describe("editorial registration", () => {
).rejects.toEqual( ).rejects.toEqual(
new RegistrationValidationError( new RegistrationValidationError(
"termsVersion", "termsVersion",
"Bitte akzeptieren Sie die Nutzungs- und Lizenzbedingungen.", "Bitte akzeptieren Sie die aktuell gültigen Nutzungs- und Lizenzbedingungen.",
), ),
); );
await expect( await expect(
@@ -118,6 +125,87 @@ describe("editorial registration", () => {
); );
}); });
test.each<[string, RegistrationChange, string]>([
["companyName", { companyName: " " }, "Bitte geben Sie den Namen der Redaktion oder des Unternehmens an."],
["contactName", { contactName: " " }, "Bitte geben Sie eine Ansprechperson an."],
["email", { email: "keine-adresse" }, "Bitte geben Sie eine gültige E-Mail-Adresse an."],
["password", { password: "" }, "Bitte geben Sie ein Passwort an."],
[
"addressLine1",
{ billingAddress: { ...validRegistration.billingAddress, addressLine1: " " } },
"Bitte geben Sie Straße und Hausnummer an.",
],
[
"postalCode",
{ billingAddress: { ...validRegistration.billingAddress, postalCode: " " } },
"Bitte geben Sie die Postleitzahl an.",
],
[
"city",
{ billingAddress: { ...validRegistration.billingAddress, city: " " } },
"Bitte geben Sie den Ort an.",
],
[
"countryCode",
{ billingAddress: { ...validRegistration.billingAddress, countryCode: "Deutschland" } },
"Bitte geben Sie einen zweistelligen ISO-Ländercode an.",
],
])("rejects missing or malformed required %s data on the server", async (field, change, message) => {
const { auth, repo, service } = createService();
const input = {
...validRegistration,
...change,
billingAddress: change.billingAddress ?? validRegistration.billingAddress,
};
await expect(service.register(input)).rejects.toEqual(
new RegistrationValidationError(field as RegistrationValidationError["field"], message),
);
expect(auth.signUpEmail).not.toHaveBeenCalled();
expect(repo.createEditorial).not.toHaveBeenCalled();
});
test("pins the accepted terms to the server-owned current version", async () => {
const { auth, service } = createService();
await expect(
service.register({ ...validRegistration, termsVersion: "arbitrary-browser-value" }),
).rejects.toEqual(
new RegistrationValidationError(
"termsVersion",
"Bitte akzeptieren Sie die aktuell gültigen Nutzungs- und Lizenzbedingungen.",
),
);
expect(auth.signUpEmail).not.toHaveBeenCalled();
});
test("compensates a failed editorial transaction by removing the new unverified auth identity", async () => {
const { audit, repo, service } = createService();
const persistenceError = new Error("editorial persistence failed");
repo.createEditorial.mockRejectedValue(persistenceError);
await expect(service.register(validRegistration)).rejects.toBe(persistenceError);
expect(repo.removeUnverifiedAuthIdentity).toHaveBeenCalledWith({
email: "mara.muster@example.com",
userId: "user-1",
});
expect(audit.recordRegistrationCompensationFailure).not.toHaveBeenCalled();
});
test("keeps the original persistence failure and audits a failed compensation without request data", async () => {
const { audit, repo, service } = createService();
const persistenceError = new Error("editorial persistence failed");
repo.createEditorial.mockRejectedValue(persistenceError);
repo.removeUnverifiedAuthIdentity.mockRejectedValue(new Error("cleanup failed"));
await expect(service.register(validRegistration)).rejects.toBe(persistenceError);
expect(audit.recordRegistrationCompensationFailure).toHaveBeenCalledWith({ userId: "user-1" });
});
test("moves a verified account from pending email to pending approval", async () => { test("moves a verified account from pending email to pending approval", async () => {
const { audit, repo, service } = createService(); const { audit, repo, service } = createService();
+172 -24
View File
@@ -2,10 +2,34 @@ import "server-only";
import { and, eq } from "drizzle-orm"; import { and, eq } from "drizzle-orm";
import type { NodePgDatabase } from "drizzle-orm/node-postgres"; import type { NodePgDatabase } from "drizzle-orm/node-postgres";
import { z } from "zod";
import { auditEvents, billingAddressVersions, editorialAccounts, users } from "@/db/schema"; import {
accounts,
auditEvents,
billingAddressVersions,
editorialAccounts,
sessions,
users,
verifications,
} from "@/db/schema";
import type * as schema from "@/db/schema"; import type * as schema from "@/db/schema";
export const CURRENT_TERMS_VERSION = "2026-08";
export type RegistrationField =
| "companyName"
| "contactName"
| "email"
| "password"
| "addressLine1"
| "postalCode"
| "city"
| "countryCode"
| "actsForBusiness"
| "termsVersion"
| "privacyAcknowledged";
export type BillingAddressInput = { export type BillingAddressInput = {
addressLine1: string; addressLine1: string;
addressLine2?: string; addressLine2?: string;
@@ -45,19 +69,18 @@ export type RegistrationAuth = {
export type EditorialRegistrationRepository = { export type EditorialRegistrationRepository = {
createEditorial(input: PendingEditorial): Promise<void>; createEditorial(input: PendingEditorial): Promise<void>;
markPendingApproval(userId: string): Promise<boolean>; markPendingApproval(userId: string): Promise<boolean>;
removeUnverifiedAuthIdentity(input: { userId: string; email: string }): Promise<boolean>;
}; };
export type RegistrationAudit = { export type RegistrationAudit = {
recordVerificationInconsistency(input: { userId: string }): Promise<void>; recordVerificationInconsistency(input: { userId: string }): Promise<void>;
recordRegistrationCompensationFailure(input: { userId: string }): Promise<void>;
}; };
export class RegistrationValidationError extends Error { export class RegistrationValidationError extends Error {
readonly name = "RegistrationValidationError"; readonly name = "RegistrationValidationError";
constructor( constructor(readonly field: RegistrationField, message: string) {
readonly field: "actsForBusiness" | "termsVersion" | "privacyAcknowledged",
message: string,
) {
super(message); super(message);
} }
} }
@@ -83,13 +106,14 @@ export function createRegistrationService({
}); });
const acceptedAt = now(); const acceptedAt = now();
try {
await repo.createEditorial({ await repo.createEditorial({
userId: result.user.id, userId: result.user.id,
name: registration.companyName, name: registration.companyName,
contactName: registration.contactName, contactName: registration.contactName,
loginEmail: registration.loginEmail, loginEmail: registration.loginEmail,
status: "pending_email", status: "pending_email",
acceptedTermsVersion: registration.termsVersion, acceptedTermsVersion: CURRENT_TERMS_VERSION,
acceptedTermsAt: acceptedAt, acceptedTermsAt: acceptedAt,
privacyAcknowledgedAt: acceptedAt, privacyAcknowledgedAt: acceptedAt,
billingAddress: { billingAddress: {
@@ -98,6 +122,21 @@ export function createRegistrationService({
...registration.billingAddress, ...registration.billingAddress,
}, },
}); });
} catch (error) {
try {
await repo.removeUnverifiedAuthIdentity({
userId: result.user.id,
email: registration.loginEmail,
});
} catch {
try {
await audit.recordRegistrationCompensationFailure({ userId: result.user.id });
} catch {
// Preserve the original editorial persistence error.
}
}
throw error;
}
await auth.sendVerificationEmail({ email: registration.loginEmail }); await auth.sendVerificationEmail({ email: registration.loginEmail });
return { status: "pending_email" }; return { status: "pending_email" };
@@ -112,12 +151,12 @@ export function createRegistrationService({
}; };
} }
export function createEditorialRegistrationRepository(database: NodePgDatabase<typeof schema>): { export function createEditorialRegistrationRepository(
createEditorial(input: PendingEditorial): Promise<void>; database: NodePgDatabase<typeof schema>,
markPendingApproval(userId: string): Promise<boolean>; ): EditorialRegistrationRepository &
recordVerificationInconsistency(input: { userId: string }): Promise<void>; RegistrationAudit & {
canCreateSession(userId: string): Promise<boolean>; canCreateSession(userId: string): Promise<boolean>;
} { } {
return { return {
async createEditorial(input) { async createEditorial(input) {
await database.transaction(async (transaction) => { await database.transaction(async (transaction) => {
@@ -219,6 +258,58 @@ export function createEditorialRegistrationRepository(database: NodePgDatabase<t
}); });
}, },
async recordRegistrationCompensationFailure({ userId }) {
await database.insert(auditEvents).values({
eventType: "registration_auth_compensation_failed",
actorUserId: userId,
actorType: "system",
entityType: "user",
entityId: userId,
newValues: { reason: "editorial_persistence_failed" },
});
},
async removeUnverifiedAuthIdentity({ userId, email }) {
return database.transaction(async (transaction) => {
const [user] = await transaction
.select({ id: users.id, emailVerified: users.emailVerified, role: users.role })
.from(users)
.where(eq(users.id, userId))
.limit(1);
if (!user || user.emailVerified || user.role !== "EDITORIAL") {
return false;
}
const [existingEditorial] = await transaction
.select({ id: editorialAccounts.id })
.from(editorialAccounts)
.where(eq(editorialAccounts.userId, userId))
.limit(1);
if (existingEditorial) {
return false;
}
await transaction.delete(sessions).where(eq(sessions.userId, userId));
await transaction.delete(accounts).where(eq(accounts.userId, userId));
await transaction.delete(verifications).where(eq(verifications.identifier, email));
const [deletedUser] = await transaction
.delete(users)
.where(
and(
eq(users.id, userId),
eq(users.emailVerified, false),
eq(users.role, "EDITORIAL"),
),
)
.returning({ id: users.id });
return Boolean(deletedUser);
});
},
async canCreateSession(userId) { async canCreateSession(userId) {
const [principal] = await database const [principal] = await database
.select({ role: users.role, status: editorialAccounts.status }) .select({ role: users.role, status: editorialAccounts.status })
@@ -237,7 +328,6 @@ function validateRegistration(input: RegistrationInput): {
contactName: string; contactName: string;
loginEmail: string; loginEmail: string;
password: string; password: string;
termsVersion: string;
billingAddress: BillingAddressInput; billingAddress: BillingAddressInput;
} { } {
if (!input.actsForBusiness) { if (!input.actsForBusiness) {
@@ -246,10 +336,10 @@ function validateRegistration(input: RegistrationInput): {
"Bitte bestätigen Sie, dass Sie im Namen eines Unternehmens oder einer Redaktion handeln.", "Bitte bestätigen Sie, dass Sie im Namen eines Unternehmens oder einer Redaktion handeln.",
); );
} }
if (!input.termsVersion.trim()) { if (trim(input.termsVersion) !== CURRENT_TERMS_VERSION) {
throw new RegistrationValidationError( throw new RegistrationValidationError(
"termsVersion", "termsVersion",
"Bitte akzeptieren Sie die Nutzungs- und Lizenzbedingungen.", "Bitte akzeptieren Sie die aktuell gültigen Nutzungs- und Lizenzbedingungen.",
); );
} }
if (!input.privacyAcknowledged) { if (!input.privacyAcknowledged) {
@@ -259,18 +349,76 @@ function validateRegistration(input: RegistrationInput): {
); );
} }
const companyName = trim(input.companyName);
if (!companyName) {
throw new RegistrationValidationError(
"companyName",
"Bitte geben Sie den Namen der Redaktion oder des Unternehmens an.",
);
}
const contactName = trim(input.contactName);
if (!contactName) {
throw new RegistrationValidationError("contactName", "Bitte geben Sie eine Ansprechperson an.");
}
const loginEmail = trim(input.email).toLowerCase();
if (!z.email().safeParse(loginEmail).success) {
throw new RegistrationValidationError("email", "Bitte geben Sie eine gültige E-Mail-Adresse an.");
}
const password = typeof input.password === "string" ? input.password : "";
if (!password) {
throw new RegistrationValidationError("password", "Bitte geben Sie ein Passwort an.");
}
if (password.length < 8) {
throw new RegistrationValidationError(
"password",
"Bitte verwenden Sie ein Passwort mit mindestens acht Zeichen.",
);
}
const addressLine1 = trim(input.billingAddress?.addressLine1);
if (!addressLine1) {
throw new RegistrationValidationError(
"addressLine1",
"Bitte geben Sie Straße und Hausnummer an.",
);
}
const postalCode = trim(input.billingAddress?.postalCode);
if (!postalCode) {
throw new RegistrationValidationError("postalCode", "Bitte geben Sie die Postleitzahl an.");
}
const city = trim(input.billingAddress?.city);
if (!city) {
throw new RegistrationValidationError("city", "Bitte geben Sie den Ort an.");
}
const countryCode = trim(input.billingAddress?.countryCode).toUpperCase();
if (!/^[A-Z]{2}$/.test(countryCode)) {
throw new RegistrationValidationError(
"countryCode",
"Bitte geben Sie einen zweistelligen ISO-Ländercode an.",
);
}
return { return {
companyName: input.companyName.trim(), companyName,
contactName: input.contactName.trim(), contactName,
loginEmail: input.email.trim().toLowerCase(), loginEmail,
password: input.password, password,
termsVersion: input.termsVersion.trim(),
billingAddress: { billingAddress: {
addressLine1: input.billingAddress.addressLine1.trim(), addressLine1,
addressLine2: input.billingAddress.addressLine2?.trim() || undefined, addressLine2: trim(input.billingAddress?.addressLine2) || undefined,
postalCode: input.billingAddress.postalCode.trim(), postalCode,
city: input.billingAddress.city.trim(), city,
countryCode: input.billingAddress.countryCode.trim().toUpperCase(), countryCode,
}, },
}; };
} }
function trim(value: unknown): string {
return typeof value === "string" ? value.trim() : "";
}