feat: add editorial registration and authentication
This commit is contained in:
1 parent
7acaacb92e
commit
9b22752ef2
20 files changed
+1728
-20
No files matched your search
@@ -0,0 +1,38 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { env } from "@/config/env";
|
||||
import { LoginForm } from "@/modules/auth/public-forms";
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<main className="public-account-page">
|
||||
<header className="masthead">
|
||||
<Link className="wordmark" href="/">
|
||||
Leon Tonhäuser
|
||||
</Link>
|
||||
<span className="section-label">Redaktionsportal</span>
|
||||
</header>
|
||||
<section className="account-panel" aria-labelledby="login-title">
|
||||
<p className="eyebrow">Zugang</p>
|
||||
<h1 id="login-title">Anmelden</h1>
|
||||
<p className="lede">Melden Sie sich mit der E-Mail-Adresse Ihrer Redaktion an.</p>
|
||||
<LoginForm />
|
||||
<nav className="account-links" aria-label="Zugang verwalten">
|
||||
<Link href="/passwort-vergessen">Passwort vergessen?</Link>
|
||||
<Link href="/registrieren">Neue Redaktion registrieren</Link>
|
||||
</nav>
|
||||
</section>
|
||||
<LegalFooter imprint={env.LEGAL_IMPRINT_URL} privacy={env.LEGAL_PRIVACY_URL} terms={env.LEGAL_TERMS_URL} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function LegalFooter({ imprint, privacy, terms }: { imprint: string; privacy: string; terms: string }) {
|
||||
return (
|
||||
<footer className="public-footer">
|
||||
<a href={imprint}>Impressum</a>
|
||||
<a href={privacy}>Datenschutz</a>
|
||||
<a href={terms}>Nutzungsbedingungen</a>
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { PasswordResetRequestForm } from "@/modules/auth/public-forms";
|
||||
|
||||
export default function ForgotPasswordPage() {
|
||||
return (
|
||||
<main className="public-account-page">
|
||||
<header className="masthead">
|
||||
<Link className="wordmark" href="/">
|
||||
Leon Tonhäuser
|
||||
</Link>
|
||||
<span className="section-label">Redaktionsportal</span>
|
||||
</header>
|
||||
<section className="account-panel" aria-labelledby="forgot-password-title">
|
||||
<p className="eyebrow">Zugang</p>
|
||||
<h1 id="forgot-password-title">Passwort vergessen?</h1>
|
||||
<p className="lede">Fordern Sie einen Link zum Zurücksetzen Ihres Passworts an.</p>
|
||||
<PasswordResetRequestForm />
|
||||
<nav className="account-links" aria-label="Zurück zur Anmeldung">
|
||||
<Link href="/anmelden">Zur Anmeldung</Link>
|
||||
</nav>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { PasswordResetForm } from "@/modules/auth/public-forms";
|
||||
|
||||
export default async function ResetPasswordPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<{ token?: string }>;
|
||||
}) {
|
||||
const { token } = await searchParams;
|
||||
|
||||
return (
|
||||
<main className="public-account-page">
|
||||
<header className="masthead">
|
||||
<Link className="wordmark" href="/">
|
||||
Leon Tonhäuser
|
||||
</Link>
|
||||
<span className="section-label">Redaktionsportal</span>
|
||||
</header>
|
||||
<section className="account-panel" aria-labelledby="reset-password-title">
|
||||
<p className="eyebrow">Zugang</p>
|
||||
<h1 id="reset-password-title">Neues Passwort setzen</h1>
|
||||
<p className="lede">Wählen Sie ein neues Passwort für den Zugang Ihrer Redaktion.</p>
|
||||
<PasswordResetForm token={token} />
|
||||
<nav className="account-links" aria-label="Zurück zur Anmeldung">
|
||||
<Link href="/anmelden">Zur Anmeldung</Link>
|
||||
</nav>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import Link from "next/link";
|
||||
|
||||
export default function RegistrationConfirmedPage() {
|
||||
return (
|
||||
<main className="public-account-page">
|
||||
<header className="masthead">
|
||||
<Link className="wordmark" href="/">
|
||||
Leon Tonhäuser
|
||||
</Link>
|
||||
<span className="section-label">Redaktionsportal</span>
|
||||
</header>
|
||||
<section className="account-panel" aria-labelledby="confirmation-title">
|
||||
<p className="eyebrow">Registrierung</p>
|
||||
<h1 id="confirmation-title">Vielen Dank.</h1>
|
||||
<p className="lede">
|
||||
Bitte folgen Sie den weiteren Hinweisen, die wir Ihnen gegebenenfalls zusenden. Danach
|
||||
prüfen wir Ihre Registrierung.
|
||||
</p>
|
||||
<Link className="primary-action" href="/anmelden">
|
||||
Zur Anmeldung
|
||||
</Link>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { env } from "@/config/env";
|
||||
import { registerEditorial } from "@/modules/auth/auth";
|
||||
import { RegistrationValidationError } from "@/modules/auth/registration";
|
||||
import {
|
||||
RegistrationForm,
|
||||
type RegistrationFormState,
|
||||
} from "@/modules/auth/public-forms";
|
||||
|
||||
export default function RegistrationPage() {
|
||||
return (
|
||||
<main className="public-account-page">
|
||||
<header className="masthead">
|
||||
<Link className="wordmark" href="/">
|
||||
Leon Tonhäuser
|
||||
</Link>
|
||||
<span className="section-label">Redaktionsportal</span>
|
||||
</header>
|
||||
<section className="account-panel account-panel-wide" aria-labelledby="registration-title">
|
||||
<p className="eyebrow">B2B-Zugang</p>
|
||||
<h1 id="registration-title">Redaktion registrieren</h1>
|
||||
<p className="lede">
|
||||
Das Redaktionsportal steht ausschließlich Unternehmen und Redaktionen zur Verfügung.
|
||||
</p>
|
||||
<RegistrationForm
|
||||
action={registerAction}
|
||||
legalUrls={{
|
||||
imprint: env.LEGAL_IMPRINT_URL,
|
||||
privacy: env.LEGAL_PRIVACY_URL,
|
||||
terms: env.LEGAL_TERMS_URL,
|
||||
}}
|
||||
/>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
async function registerAction(
|
||||
_state: RegistrationFormState,
|
||||
formData: FormData,
|
||||
): Promise<RegistrationFormState> {
|
||||
"use server";
|
||||
|
||||
try {
|
||||
await registerEditorial({
|
||||
companyName: text(formData, "companyName"),
|
||||
contactName: text(formData, "contactName"),
|
||||
email: text(formData, "email"),
|
||||
password: text(formData, "password"),
|
||||
billingAddress: {
|
||||
addressLine1: text(formData, "addressLine1"),
|
||||
addressLine2: text(formData, "addressLine2") || undefined,
|
||||
postalCode: text(formData, "postalCode"),
|
||||
city: text(formData, "city"),
|
||||
countryCode: text(formData, "countryCode"),
|
||||
},
|
||||
actsForBusiness: formData.has("actsForBusiness"),
|
||||
termsVersion: formData.has("termsAccepted") ? text(formData, "termsVersion") : "",
|
||||
privacyAcknowledged: formData.has("privacyAcknowledged"),
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof RegistrationValidationError) {
|
||||
return { errors: { [error.field]: error.message } };
|
||||
}
|
||||
}
|
||||
|
||||
redirect("/registrieren/bestaetigt");
|
||||
}
|
||||
|
||||
function text(formData: FormData, name: string): string {
|
||||
const value = formData.get(name);
|
||||
return typeof value === "string" ? value : "";
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { toNextJsHandler } from "better-auth/next-js";
|
||||
|
||||
import { auth } from "@/modules/auth/auth";
|
||||
|
||||
export const { GET, POST } = toNextJsHandler(auth);
|
||||
@@ -138,3 +138,141 @@ a {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
.public-account-page {
|
||||
display: grid;
|
||||
min-height: 100vh;
|
||||
grid-template-rows: auto 1fr auto;
|
||||
padding: clamp(1.25rem, 3vw, 2.75rem);
|
||||
}
|
||||
|
||||
.account-panel {
|
||||
width: min(100%, 37rem);
|
||||
align-self: center;
|
||||
padding-block: clamp(4rem, 10vh, 7rem);
|
||||
}
|
||||
|
||||
.account-panel-wide {
|
||||
width: min(100%, 48rem);
|
||||
}
|
||||
|
||||
.account-panel h1 {
|
||||
max-width: 12ch;
|
||||
margin: 0;
|
||||
font-size: clamp(2.6rem, 6vw, 5.5rem);
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.06em;
|
||||
line-height: 0.92;
|
||||
}
|
||||
|
||||
.account-panel .lede {
|
||||
margin-top: 1.75rem;
|
||||
}
|
||||
|
||||
.account-form {
|
||||
display: grid;
|
||||
gap: 1.25rem;
|
||||
margin-top: 2.5rem;
|
||||
}
|
||||
|
||||
.account-form label,
|
||||
.acknowledgements legend {
|
||||
display: grid;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 650;
|
||||
letter-spacing: 0.01em;
|
||||
}
|
||||
|
||||
.account-form input:not([type="checkbox"]) {
|
||||
width: 100%;
|
||||
min-height: 3.1rem;
|
||||
border: 1px solid var(--ink);
|
||||
border-radius: 0;
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
font: inherit;
|
||||
font-weight: 400;
|
||||
padding: 0.75rem;
|
||||
}
|
||||
|
||||
.form-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.acknowledgements {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
margin: 0;
|
||||
padding: 1.25rem 0;
|
||||
border: 0;
|
||||
border-top: 1px solid var(--line);
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.acknowledgements legend {
|
||||
padding: 0;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.checkbox-label {
|
||||
grid-template-columns: 1rem minmax(0, 1fr);
|
||||
align-items: start;
|
||||
font-weight: 400 !important;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.checkbox-label input {
|
||||
width: 1rem;
|
||||
height: 1rem;
|
||||
margin: 0.12rem 0 0;
|
||||
accent-color: var(--ink);
|
||||
}
|
||||
|
||||
.checkbox-label a,
|
||||
.account-links a,
|
||||
.public-footer a,
|
||||
.legal-link {
|
||||
text-underline-offset: 0.17em;
|
||||
}
|
||||
|
||||
.field-error {
|
||||
margin: -0.25rem 0 0;
|
||||
color: #9d0e0e;
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.form-note {
|
||||
max-width: 44rem;
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.account-links,
|
||||
.public-footer {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem 1.25rem;
|
||||
margin-top: 1rem;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.public-footer {
|
||||
padding-top: 1rem;
|
||||
border-top: 1px solid var(--line);
|
||||
color: var(--muted);
|
||||
font-size: 0.75rem;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
@media (max-width: 40rem) {
|
||||
.form-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import "server-only";
|
||||
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
|
||||
import { users } from "@/db/schema";
|
||||
import type * as schema from "@/db/schema";
|
||||
|
||||
export type AdminBootstrapInput = {
|
||||
email: string;
|
||||
name: string;
|
||||
password: string;
|
||||
};
|
||||
|
||||
export type AdminBootstrapAuth = {
|
||||
signUpEmail(input: { email: string; name: string; password: string }): Promise<{ user: { id: string } }>;
|
||||
sendVerificationEmail(input: { email: string }): Promise<void>;
|
||||
};
|
||||
|
||||
export type AdminBootstrapRepository = {
|
||||
countAdmins(): Promise<number>;
|
||||
findUserByEmail(email: string): Promise<{ id: string } | undefined>;
|
||||
promoteUserToAdmin(userId: string): Promise<void>;
|
||||
};
|
||||
|
||||
export function createAdminBootstrapService({
|
||||
auth,
|
||||
repo,
|
||||
}: {
|
||||
auth: AdminBootstrapAuth;
|
||||
repo: AdminBootstrapRepository;
|
||||
}) {
|
||||
return {
|
||||
async bootstrap(input: AdminBootstrapInput): Promise<{ status: "created" | "already_configured" }> {
|
||||
if ((await repo.countAdmins()) > 0) {
|
||||
return { status: "already_configured" };
|
||||
}
|
||||
|
||||
const email = input.email.trim().toLowerCase();
|
||||
const existingUser = await repo.findUserByEmail(email);
|
||||
const user =
|
||||
existingUser ??
|
||||
(await auth.signUpEmail({
|
||||
email,
|
||||
name: input.name.trim(),
|
||||
password: input.password,
|
||||
})).user;
|
||||
|
||||
await repo.promoteUserToAdmin(user.id);
|
||||
await auth.sendVerificationEmail({ email });
|
||||
return { status: "created" };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createAdminBootstrapRepository(database: NodePgDatabase<typeof schema>): AdminBootstrapRepository {
|
||||
return {
|
||||
async countAdmins() {
|
||||
const [result] = await database
|
||||
.select({ count: sql<number>`count(*)::int` })
|
||||
.from(users)
|
||||
.where(eq(users.role, "ADMIN"));
|
||||
return result.count;
|
||||
},
|
||||
async findUserByEmail(email) {
|
||||
const [user] = await database
|
||||
.select({ id: users.id })
|
||||
.from(users)
|
||||
.where(eq(users.email, email))
|
||||
.limit(1);
|
||||
return user;
|
||||
},
|
||||
async promoteUserToAdmin(userId) {
|
||||
await database
|
||||
.update(users)
|
||||
.set({ role: "ADMIN", updatedAt: new Date() })
|
||||
.where(eq(users.id, userId));
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import { auth } from "./auth";
|
||||
|
||||
test("rejects direct Better Auth sign-up requests that bypass B2B registration", async () => {
|
||||
const response = await auth.handler(
|
||||
new Request("http://localhost:3000/api/auth/sign-up/email", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
email: "bypass@example.com",
|
||||
name: "Bypass",
|
||||
password: "sicheres-passwort-123",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import "server-only";
|
||||
|
||||
import { drizzleAdapter } from "@better-auth/drizzle-adapter";
|
||||
import { betterAuth } from "better-auth";
|
||||
import { APIError, createAuthMiddleware } from "better-auth/api";
|
||||
|
||||
import { env } from "@/config/env";
|
||||
import { db } from "@/db/client";
|
||||
import { accounts, sessions, users, verifications } from "@/db/schema";
|
||||
import { mailer } from "@/modules/mail/mailer";
|
||||
|
||||
import {
|
||||
createEditorialRegistrationRepository,
|
||||
createRegistrationService,
|
||||
type RegistrationInput,
|
||||
} from "./registration";
|
||||
|
||||
const registrationRepository = createEditorialRegistrationRepository(db);
|
||||
|
||||
export const auth = betterAuth({
|
||||
baseURL: env.BETTER_AUTH_URL,
|
||||
secret: env.BETTER_AUTH_SECRET,
|
||||
database: drizzleAdapter(db, {
|
||||
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: {
|
||||
enabled: true,
|
||||
requireEmailVerification: true,
|
||||
autoSignIn: false,
|
||||
resetPasswordTokenExpiresIn: 60 * 60,
|
||||
revokeSessionsOnPasswordReset: true,
|
||||
async sendResetPassword({ user, url }) {
|
||||
await mailer.sendPasswordReset({ to: user.email, resetUrl: url });
|
||||
},
|
||||
},
|
||||
emailVerification: {
|
||||
sendOnSignUp: false,
|
||||
autoSignInAfterVerification: false,
|
||||
expiresIn: 60 * 60,
|
||||
async sendVerificationEmail({ user, url }) {
|
||||
await mailer.sendVerification({ to: user.email, verificationUrl: url });
|
||||
},
|
||||
async afterEmailVerification(user) {
|
||||
await registrationService.onEmailVerified(user.id);
|
||||
},
|
||||
},
|
||||
databaseHooks: {
|
||||
session: {
|
||||
create: {
|
||||
async before(session) {
|
||||
return registrationRepository.canCreateSession(session.userId);
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export const registrationService = createRegistrationService({
|
||||
auth: {
|
||||
async signUpEmail({ email, name, password }) {
|
||||
return auth.api.signUpEmail({ body: { email, name, password } });
|
||||
},
|
||||
async sendVerificationEmail({ email }) {
|
||||
await auth.api.sendVerificationEmail({
|
||||
body: { email, callbackURL: "/registrieren/bestaetigt" },
|
||||
});
|
||||
},
|
||||
},
|
||||
repo: registrationRepository,
|
||||
audit: registrationRepository,
|
||||
});
|
||||
|
||||
export function registerEditorial(input: RegistrationInput): Promise<{ status: "pending_email" }> {
|
||||
return registrationService.register(input);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import { createAuthClient } from "better-auth/react";
|
||||
|
||||
export const authClient = createAuthClient();
|
||||
@@ -0,0 +1,41 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import { RegistrationForm } from "./public-forms";
|
||||
|
||||
test("registration presents separate B2B, terms, and privacy acknowledgements", () => {
|
||||
render(
|
||||
<RegistrationForm
|
||||
action={vi.fn()}
|
||||
legalUrls={{
|
||||
imprint: "https://example.com/impressum",
|
||||
privacy: "https://example.com/datenschutz",
|
||||
terms: "https://example.com/nutzungsbedingungen",
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.getByRole("checkbox", {
|
||||
name: /im namen einer redaktion oder eines unternehmens/i,
|
||||
}),
|
||||
).toHaveProperty("required", true);
|
||||
expect(screen.getByRole("checkbox", { name: /nutzungs- und lizenzbedingungen/i })).toHaveProperty(
|
||||
"required",
|
||||
true,
|
||||
);
|
||||
expect(screen.getByRole("checkbox", { name: /datenschutzerklärung/i })).toHaveProperty(
|
||||
"required",
|
||||
true,
|
||||
);
|
||||
expect(screen.getByRole("link", { name: /nutzungs- und lizenzbedingungen/i })).toHaveProperty(
|
||||
"href",
|
||||
"https://example.com/nutzungsbedingungen",
|
||||
);
|
||||
expect(screen.getByRole("link", { name: /datenschutzerklärung/i })).toHaveProperty(
|
||||
"href",
|
||||
"https://example.com/datenschutz",
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,256 @@
|
||||
"use client";
|
||||
|
||||
import { type FormEvent, useActionState, useState } from "react";
|
||||
|
||||
import { authClient } from "./client";
|
||||
|
||||
export type RegistrationFormState = {
|
||||
errors?: Partial<
|
||||
Record<"actsForBusiness" | "termsVersion" | "privacyAcknowledged", string>
|
||||
>;
|
||||
};
|
||||
|
||||
export type RegistrationFormAction = (
|
||||
state: RegistrationFormState,
|
||||
formData: FormData,
|
||||
) => Promise<RegistrationFormState>;
|
||||
|
||||
export type LegalUrls = {
|
||||
imprint: string;
|
||||
privacy: string;
|
||||
terms: string;
|
||||
};
|
||||
|
||||
const initialRegistrationState: RegistrationFormState = {};
|
||||
|
||||
export function RegistrationForm({
|
||||
action,
|
||||
legalUrls,
|
||||
}: {
|
||||
action: RegistrationFormAction;
|
||||
legalUrls: LegalUrls;
|
||||
}) {
|
||||
const [state, formAction, pending] = useActionState(action, initialRegistrationState);
|
||||
|
||||
return (
|
||||
<form action={formAction} className="account-form">
|
||||
<input name="termsVersion" type="hidden" value="2026-08" />
|
||||
<div className="form-grid">
|
||||
<label>
|
||||
Redaktion oder Unternehmen
|
||||
<input autoComplete="organization" name="companyName" required />
|
||||
</label>
|
||||
<label>
|
||||
Ansprechpartner:in
|
||||
<input autoComplete="name" name="contactName" required />
|
||||
</label>
|
||||
<label>
|
||||
E-Mail-Adresse
|
||||
<input autoComplete="email" name="email" required type="email" />
|
||||
</label>
|
||||
<label>
|
||||
Passwort
|
||||
<input autoComplete="new-password" minLength={8} name="password" required type="password" />
|
||||
</label>
|
||||
<label>
|
||||
Straße und Hausnummer
|
||||
<input autoComplete="address-line1" name="addressLine1" required />
|
||||
</label>
|
||||
<label>
|
||||
Adresszusatz
|
||||
<input autoComplete="address-line2" name="addressLine2" />
|
||||
</label>
|
||||
<label>
|
||||
Postleitzahl
|
||||
<input autoComplete="postal-code" name="postalCode" required />
|
||||
</label>
|
||||
<label>
|
||||
Ort
|
||||
<input autoComplete="address-level2" name="city" required />
|
||||
</label>
|
||||
<label>
|
||||
Land (ISO-Code)
|
||||
<input
|
||||
autoComplete="country"
|
||||
defaultValue="DE"
|
||||
maxLength={2}
|
||||
name="countryCode"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<fieldset className="acknowledgements">
|
||||
<legend>Verbindliche Angaben</legend>
|
||||
<label className="checkbox-label">
|
||||
<input name="actsForBusiness" required type="checkbox" />
|
||||
Ich handle im Namen einer Redaktion oder eines Unternehmens.
|
||||
</label>
|
||||
<FieldError message={state.errors?.actsForBusiness} />
|
||||
<label className="checkbox-label">
|
||||
<input name="termsAccepted" required type="checkbox" />
|
||||
Ich akzeptiere die{" "}
|
||||
<a href={legalUrls.terms} rel="noreferrer" target="_blank">
|
||||
Nutzungs- und Lizenzbedingungen
|
||||
</a>
|
||||
.
|
||||
</label>
|
||||
<FieldError message={state.errors?.termsVersion} />
|
||||
<label className="checkbox-label">
|
||||
<input name="privacyAcknowledged" required type="checkbox" />
|
||||
Ich habe die{" "}
|
||||
<a href={legalUrls.privacy} rel="noreferrer" target="_blank">
|
||||
Datenschutzerklärung
|
||||
</a>{" "}
|
||||
zur Kenntnis genommen.
|
||||
</label>
|
||||
<FieldError message={state.errors?.privacyAcknowledged} />
|
||||
</fieldset>
|
||||
|
||||
<button className="primary-action" disabled={pending} type="submit">
|
||||
{pending ? "Registrierung wird gesendet …" : "Registrierung senden"}
|
||||
</button>
|
||||
<p className="form-note">
|
||||
Wir informieren Sie auf der nächsten Seite über den weiteren Ablauf.
|
||||
</p>
|
||||
<a className="legal-link" href={legalUrls.imprint} rel="noreferrer" target="_blank">
|
||||
Impressum
|
||||
</a>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export function LoginForm() {
|
||||
const [error, setError] = useState<string>();
|
||||
const [pending, setPending] = useState(false);
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setPending(true);
|
||||
setError(undefined);
|
||||
|
||||
const formData = new FormData(event.currentTarget);
|
||||
const result = await authClient.signIn.email({
|
||||
email: readText(formData, "email").trim().toLowerCase(),
|
||||
password: readText(formData, "password"),
|
||||
callbackURL: "/",
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
setError("Die Anmeldung war nicht erfolgreich. Bitte prüfen Sie Ihre Angaben.");
|
||||
setPending(false);
|
||||
return;
|
||||
}
|
||||
|
||||
window.location.assign(result.data?.url ?? "/");
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="account-form" onSubmit={submit}>
|
||||
<label>
|
||||
E-Mail-Adresse
|
||||
<input autoComplete="email" name="email" required type="email" />
|
||||
</label>
|
||||
<label>
|
||||
Passwort
|
||||
<input autoComplete="current-password" name="password" required type="password" />
|
||||
</label>
|
||||
<FieldError message={error} />
|
||||
<button className="primary-action" disabled={pending} type="submit">
|
||||
{pending ? "Anmeldung wird geprüft …" : "Anmelden"}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export function PasswordResetRequestForm() {
|
||||
const [submitted, setSubmitted] = useState(false);
|
||||
const [pending, setPending] = useState(false);
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setPending(true);
|
||||
const formData = new FormData(event.currentTarget);
|
||||
|
||||
try {
|
||||
await authClient.requestPasswordReset({
|
||||
email: readText(formData, "email").trim().toLowerCase(),
|
||||
redirectTo: `${window.location.origin}/passwort-zuruecksetzen`,
|
||||
});
|
||||
} finally {
|
||||
setSubmitted(true);
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (submitted) {
|
||||
return (
|
||||
<p className="form-note" role="status">
|
||||
Falls ein Zugang zu dieser Adresse gehört, erhalten Sie in Kürze weitere Hinweise.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="account-form" onSubmit={submit}>
|
||||
<label>
|
||||
E-Mail-Adresse
|
||||
<input autoComplete="email" name="email" required type="email" />
|
||||
</label>
|
||||
<button className="primary-action" disabled={pending} type="submit">
|
||||
{pending ? "Anfrage wird gesendet …" : "Link anfordern"}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export function PasswordResetForm({ token }: { token?: string }) {
|
||||
const [message, setMessage] = useState<string>();
|
||||
const [pending, setPending] = useState(false);
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setPending(true);
|
||||
const formData = new FormData(event.currentTarget);
|
||||
|
||||
try {
|
||||
await authClient.resetPassword({ newPassword: readText(formData, "password"), token });
|
||||
} finally {
|
||||
setMessage("Wenn der Link gültig war, wurde Ihr Passwort aktualisiert.");
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (message) {
|
||||
return (
|
||||
<p className="form-note" role="status">
|
||||
{message}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="account-form" onSubmit={submit}>
|
||||
<label>
|
||||
Neues Passwort
|
||||
<input autoComplete="new-password" minLength={8} name="password" required type="password" />
|
||||
</label>
|
||||
<button className="primary-action" disabled={pending} type="submit">
|
||||
{pending ? "Passwort wird aktualisiert …" : "Passwort aktualisieren"}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function FieldError({ message }: { message?: string }) {
|
||||
return message ? (
|
||||
<p className="field-error" role="alert">
|
||||
{message}
|
||||
</p>
|
||||
) : null;
|
||||
}
|
||||
|
||||
function readText(formData: FormData, name: string): string {
|
||||
const value = formData.get(name);
|
||||
return typeof value === "string" ? value : "";
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
|
||||
import {
|
||||
RegistrationValidationError,
|
||||
createRegistrationService,
|
||||
type RegistrationInput,
|
||||
} from "./registration";
|
||||
import { createAdminBootstrapService } from "./admin-bootstrap";
|
||||
|
||||
const validRegistration: RegistrationInput = {
|
||||
companyName: "Neue Redaktion GmbH",
|
||||
contactName: "Mara Muster",
|
||||
email: "Mara.Muster@Example.com",
|
||||
password: "sicheres-passwort-123",
|
||||
billingAddress: {
|
||||
addressLine1: "Presseweg 1",
|
||||
addressLine2: "Haus B",
|
||||
postalCode: "10115",
|
||||
city: "Berlin",
|
||||
countryCode: "DE",
|
||||
},
|
||||
actsForBusiness: true,
|
||||
termsVersion: "2026-08",
|
||||
privacyAcknowledged: true,
|
||||
};
|
||||
|
||||
function createService() {
|
||||
const auth = {
|
||||
signUpEmail: vi.fn().mockResolvedValue({ user: { id: "user-1" } }),
|
||||
sendVerificationEmail: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const repo = {
|
||||
createEditorial: vi.fn().mockResolvedValue(undefined),
|
||||
markPendingApproval: vi.fn().mockResolvedValue(true),
|
||||
};
|
||||
const audit = {
|
||||
recordVerificationInconsistency: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const now = new Date("2026-08-09T10:00:00.000Z");
|
||||
|
||||
return {
|
||||
auth,
|
||||
repo,
|
||||
audit,
|
||||
service: createRegistrationService({ auth, repo, audit, now: () => now }),
|
||||
};
|
||||
}
|
||||
|
||||
describe("editorial registration", () => {
|
||||
test("creates a pending editorial and sends verification mail", async () => {
|
||||
const { auth, repo, service } = createService();
|
||||
|
||||
await expect(service.register(validRegistration)).resolves.toEqual({ status: "pending_email" });
|
||||
|
||||
expect(auth.signUpEmail).toHaveBeenCalledWith({
|
||||
email: "mara.muster@example.com",
|
||||
name: "Mara Muster",
|
||||
password: "sicheres-passwort-123",
|
||||
});
|
||||
expect(repo.createEditorial).toHaveBeenCalledWith({
|
||||
userId: "user-1",
|
||||
name: "Neue Redaktion GmbH",
|
||||
contactName: "Mara Muster",
|
||||
loginEmail: "mara.muster@example.com",
|
||||
status: "pending_email",
|
||||
acceptedTermsVersion: "2026-08",
|
||||
acceptedTermsAt: new Date("2026-08-09T10:00:00.000Z"),
|
||||
privacyAcknowledgedAt: new Date("2026-08-09T10:00:00.000Z"),
|
||||
billingAddress: {
|
||||
companyName: "Neue Redaktion GmbH",
|
||||
contactName: "Mara Muster",
|
||||
addressLine1: "Presseweg 1",
|
||||
addressLine2: "Haus B",
|
||||
postalCode: "10115",
|
||||
city: "Berlin",
|
||||
countryCode: "DE",
|
||||
},
|
||||
});
|
||||
expect(auth.sendVerificationEmail).toHaveBeenCalledWith({
|
||||
email: "mara.muster@example.com",
|
||||
});
|
||||
});
|
||||
|
||||
test("rejects a registration that is not made for a business", async () => {
|
||||
const { auth, repo, service } = createService();
|
||||
|
||||
await expect(
|
||||
service.register({ ...validRegistration, actsForBusiness: false }),
|
||||
).rejects.toEqual(
|
||||
new RegistrationValidationError(
|
||||
"actsForBusiness",
|
||||
"Bitte bestätigen Sie, dass Sie im Namen eines Unternehmens oder einer Redaktion handeln.",
|
||||
),
|
||||
);
|
||||
|
||||
expect(auth.signUpEmail).not.toHaveBeenCalled();
|
||||
expect(repo.createEditorial).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("rejects missing terms and privacy acknowledgements with stable German field errors", async () => {
|
||||
const { service } = createService();
|
||||
|
||||
await expect(
|
||||
service.register({ ...validRegistration, termsVersion: "" }),
|
||||
).rejects.toEqual(
|
||||
new RegistrationValidationError(
|
||||
"termsVersion",
|
||||
"Bitte akzeptieren Sie die Nutzungs- und Lizenzbedingungen.",
|
||||
),
|
||||
);
|
||||
await expect(
|
||||
service.register({ ...validRegistration, privacyAcknowledged: false }),
|
||||
).rejects.toEqual(
|
||||
new RegistrationValidationError(
|
||||
"privacyAcknowledged",
|
||||
"Bitte bestätigen Sie die Kenntnisnahme der Datenschutzerklärung.",
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test("moves a verified account from pending email to pending approval", async () => {
|
||||
const { audit, repo, service } = createService();
|
||||
|
||||
await service.onEmailVerified("user-1");
|
||||
|
||||
expect(repo.markPendingApproval).toHaveBeenCalledWith("user-1");
|
||||
expect(audit.recordVerificationInconsistency).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("audits a verified user without an editorial account without raw request data", async () => {
|
||||
const { audit, repo, service } = createService();
|
||||
repo.markPendingApproval.mockResolvedValue(false);
|
||||
|
||||
await service.onEmailVerified("user-without-editorial");
|
||||
|
||||
expect(audit.recordVerificationInconsistency).toHaveBeenCalledWith({
|
||||
userId: "user-without-editorial",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("bootstraps the first admin only once", async () => {
|
||||
const auth = {
|
||||
signUpEmail: vi.fn().mockResolvedValue({ user: { id: "admin-1" } }),
|
||||
sendVerificationEmail: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const repo = {
|
||||
countAdmins: vi.fn().mockResolvedValue(0),
|
||||
findUserByEmail: vi.fn().mockResolvedValue(undefined),
|
||||
promoteUserToAdmin: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const service = createAdminBootstrapService({ auth, repo });
|
||||
|
||||
await expect(
|
||||
service.bootstrap({
|
||||
email: "ADMIN@EXAMPLE.COM",
|
||||
name: "Portal Admin",
|
||||
password: "sicheres-passwort-123",
|
||||
}),
|
||||
).resolves.toEqual({ status: "created" });
|
||||
|
||||
expect(auth.signUpEmail).toHaveBeenCalledWith({
|
||||
email: "admin@example.com",
|
||||
name: "Portal Admin",
|
||||
password: "sicheres-passwort-123",
|
||||
});
|
||||
expect(repo.promoteUserToAdmin).toHaveBeenCalledWith("admin-1");
|
||||
expect(auth.sendVerificationEmail).toHaveBeenCalledWith({ email: "admin@example.com" });
|
||||
});
|
||||
@@ -0,0 +1,276 @@
|
||||
import "server-only";
|
||||
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
|
||||
import { auditEvents, billingAddressVersions, editorialAccounts, users } from "@/db/schema";
|
||||
import type * as schema from "@/db/schema";
|
||||
|
||||
export type BillingAddressInput = {
|
||||
addressLine1: string;
|
||||
addressLine2?: string;
|
||||
postalCode: string;
|
||||
city: string;
|
||||
countryCode: string;
|
||||
};
|
||||
|
||||
export type RegistrationInput = {
|
||||
companyName: string;
|
||||
contactName: string;
|
||||
email: string;
|
||||
password: string;
|
||||
billingAddress: BillingAddressInput;
|
||||
actsForBusiness: boolean;
|
||||
termsVersion: string;
|
||||
privacyAcknowledged: boolean;
|
||||
};
|
||||
|
||||
export type PendingEditorial = {
|
||||
userId: string;
|
||||
name: string;
|
||||
contactName: string;
|
||||
loginEmail: string;
|
||||
status: "pending_email";
|
||||
acceptedTermsVersion: string;
|
||||
acceptedTermsAt: Date;
|
||||
privacyAcknowledgedAt: Date;
|
||||
billingAddress: BillingAddressInput & { companyName: string; contactName: string };
|
||||
};
|
||||
|
||||
export type RegistrationAuth = {
|
||||
signUpEmail(input: { email: string; name: string; password: string }): Promise<{ user: { id: string } }>;
|
||||
sendVerificationEmail(input: { email: string }): Promise<void>;
|
||||
};
|
||||
|
||||
export type EditorialRegistrationRepository = {
|
||||
createEditorial(input: PendingEditorial): Promise<void>;
|
||||
markPendingApproval(userId: string): Promise<boolean>;
|
||||
};
|
||||
|
||||
export type RegistrationAudit = {
|
||||
recordVerificationInconsistency(input: { userId: string }): Promise<void>;
|
||||
};
|
||||
|
||||
export class RegistrationValidationError extends Error {
|
||||
readonly name = "RegistrationValidationError";
|
||||
|
||||
constructor(
|
||||
readonly field: "actsForBusiness" | "termsVersion" | "privacyAcknowledged",
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export function createRegistrationService({
|
||||
auth,
|
||||
repo,
|
||||
audit,
|
||||
now = () => new Date(),
|
||||
}: {
|
||||
auth: RegistrationAuth;
|
||||
repo: EditorialRegistrationRepository;
|
||||
audit: RegistrationAudit;
|
||||
now?: () => Date;
|
||||
}) {
|
||||
return {
|
||||
async register(input: RegistrationInput): Promise<{ status: "pending_email" }> {
|
||||
const registration = validateRegistration(input);
|
||||
const result = await auth.signUpEmail({
|
||||
email: registration.loginEmail,
|
||||
name: registration.contactName,
|
||||
password: registration.password,
|
||||
});
|
||||
const acceptedAt = now();
|
||||
|
||||
await repo.createEditorial({
|
||||
userId: result.user.id,
|
||||
name: registration.companyName,
|
||||
contactName: registration.contactName,
|
||||
loginEmail: registration.loginEmail,
|
||||
status: "pending_email",
|
||||
acceptedTermsVersion: registration.termsVersion,
|
||||
acceptedTermsAt: acceptedAt,
|
||||
privacyAcknowledgedAt: acceptedAt,
|
||||
billingAddress: {
|
||||
companyName: registration.companyName,
|
||||
contactName: registration.contactName,
|
||||
...registration.billingAddress,
|
||||
},
|
||||
});
|
||||
|
||||
await auth.sendVerificationEmail({ email: registration.loginEmail });
|
||||
return { status: "pending_email" };
|
||||
},
|
||||
|
||||
async onEmailVerified(userId: string): Promise<void> {
|
||||
const transitioned = await repo.markPendingApproval(userId);
|
||||
if (!transitioned) {
|
||||
await audit.recordVerificationInconsistency({ userId });
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createEditorialRegistrationRepository(database: NodePgDatabase<typeof schema>): {
|
||||
createEditorial(input: PendingEditorial): Promise<void>;
|
||||
markPendingApproval(userId: string): Promise<boolean>;
|
||||
recordVerificationInconsistency(input: { userId: string }): Promise<void>;
|
||||
canCreateSession(userId: string): Promise<boolean>;
|
||||
} {
|
||||
return {
|
||||
async createEditorial(input) {
|
||||
await database.transaction(async (transaction) => {
|
||||
const [user] = await transaction
|
||||
.select({ id: users.id })
|
||||
.from(users)
|
||||
.where(eq(users.id, input.userId))
|
||||
.limit(1);
|
||||
|
||||
if (!user) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [existingEditorial] = await transaction
|
||||
.select({ id: editorialAccounts.id })
|
||||
.from(editorialAccounts)
|
||||
.where(eq(editorialAccounts.userId, input.userId))
|
||||
.limit(1);
|
||||
|
||||
if (existingEditorial) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [editorial] = await transaction
|
||||
.insert(editorialAccounts)
|
||||
.values({
|
||||
userId: input.userId,
|
||||
name: input.name,
|
||||
contactName: input.contactName,
|
||||
loginEmail: input.loginEmail,
|
||||
status: input.status,
|
||||
acceptedTermsVersion: input.acceptedTermsVersion,
|
||||
acceptedTermsAt: input.acceptedTermsAt,
|
||||
privacyAcknowledgedAt: input.privacyAcknowledgedAt,
|
||||
})
|
||||
.returning({ id: editorialAccounts.id });
|
||||
|
||||
const [billingAddress] = await transaction
|
||||
.insert(billingAddressVersions)
|
||||
.values({
|
||||
editorialAccountId: editorial.id,
|
||||
companyName: input.billingAddress.companyName,
|
||||
contactName: input.billingAddress.contactName,
|
||||
addressLine1: input.billingAddress.addressLine1,
|
||||
addressLine2: input.billingAddress.addressLine2,
|
||||
postalCode: input.billingAddress.postalCode,
|
||||
city: input.billingAddress.city,
|
||||
countryCode: input.billingAddress.countryCode,
|
||||
validFrom: input.acceptedTermsAt,
|
||||
createdByUserId: input.userId,
|
||||
})
|
||||
.returning({ id: billingAddressVersions.id });
|
||||
|
||||
await transaction
|
||||
.update(editorialAccounts)
|
||||
.set({ currentBillingAddressVersionId: billingAddress.id, updatedAt: input.acceptedTermsAt })
|
||||
.where(eq(editorialAccounts.id, editorial.id));
|
||||
});
|
||||
},
|
||||
|
||||
async markPendingApproval(userId) {
|
||||
const verifiedAt = new Date();
|
||||
const [transitioned] = await database
|
||||
.update(editorialAccounts)
|
||||
.set({
|
||||
status: "pending_approval",
|
||||
emailVerifiedAt: verifiedAt,
|
||||
updatedAt: verifiedAt,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(editorialAccounts.userId, userId),
|
||||
eq(editorialAccounts.status, "pending_email"),
|
||||
),
|
||||
)
|
||||
.returning({ id: editorialAccounts.id });
|
||||
|
||||
if (transitioned) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const [existingEditorial] = await database
|
||||
.select({ id: editorialAccounts.id })
|
||||
.from(editorialAccounts)
|
||||
.where(eq(editorialAccounts.userId, userId))
|
||||
.limit(1);
|
||||
|
||||
return Boolean(existingEditorial);
|
||||
},
|
||||
|
||||
async recordVerificationInconsistency({ userId }) {
|
||||
await database.insert(auditEvents).values({
|
||||
eventType: "email_verification_without_editorial_account",
|
||||
actorUserId: userId,
|
||||
actorType: "system",
|
||||
entityType: "user",
|
||||
entityId: userId,
|
||||
newValues: { reason: "no_editorial_account" },
|
||||
});
|
||||
},
|
||||
|
||||
async canCreateSession(userId) {
|
||||
const [principal] = await database
|
||||
.select({ role: users.role, status: editorialAccounts.status })
|
||||
.from(users)
|
||||
.leftJoin(editorialAccounts, eq(editorialAccounts.userId, users.id))
|
||||
.where(eq(users.id, userId))
|
||||
.limit(1);
|
||||
|
||||
return principal?.role === "ADMIN" || principal?.status === "active";
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function validateRegistration(input: RegistrationInput): {
|
||||
companyName: string;
|
||||
contactName: string;
|
||||
loginEmail: string;
|
||||
password: string;
|
||||
termsVersion: string;
|
||||
billingAddress: BillingAddressInput;
|
||||
} {
|
||||
if (!input.actsForBusiness) {
|
||||
throw new RegistrationValidationError(
|
||||
"actsForBusiness",
|
||||
"Bitte bestätigen Sie, dass Sie im Namen eines Unternehmens oder einer Redaktion handeln.",
|
||||
);
|
||||
}
|
||||
if (!input.termsVersion.trim()) {
|
||||
throw new RegistrationValidationError(
|
||||
"termsVersion",
|
||||
"Bitte akzeptieren Sie die Nutzungs- und Lizenzbedingungen.",
|
||||
);
|
||||
}
|
||||
if (!input.privacyAcknowledged) {
|
||||
throw new RegistrationValidationError(
|
||||
"privacyAcknowledged",
|
||||
"Bitte bestätigen Sie die Kenntnisnahme der Datenschutzerklärung.",
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
companyName: input.companyName.trim(),
|
||||
contactName: input.contactName.trim(),
|
||||
loginEmail: input.email.trim().toLowerCase(),
|
||||
password: input.password,
|
||||
termsVersion: input.termsVersion.trim(),
|
||||
billingAddress: {
|
||||
addressLine1: input.billingAddress.addressLine1.trim(),
|
||||
addressLine2: input.billingAddress.addressLine2?.trim() || undefined,
|
||||
postalCode: input.billingAddress.postalCode.trim(),
|
||||
city: input.billingAddress.city.trim(),
|
||||
countryCode: input.billingAddress.countryCode.trim().toUpperCase(),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import { createMailer } from "./mailer";
|
||||
|
||||
test("sends a verification link through the configured SMTP boundary", async () => {
|
||||
const transport = { sendMail: vi.fn().mockResolvedValue({ messageId: "message-1" }) };
|
||||
const mailer = createMailer({ from: "portal@example.com", transport });
|
||||
|
||||
await mailer.sendVerification({
|
||||
to: "editorial@example.com",
|
||||
verificationUrl: "https://portal.example.com/api/auth/verify-email?token=secret-token",
|
||||
});
|
||||
|
||||
expect(transport.sendMail).toHaveBeenCalledWith({
|
||||
from: "portal@example.com",
|
||||
to: "editorial@example.com",
|
||||
subject: "Bitte bestätigen Sie Ihre E-Mail-Adresse",
|
||||
text: expect.stringContaining(
|
||||
"https://portal.example.com/api/auth/verify-email?token=secret-token",
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
test("sends an approval notice without leaking SMTP credentials", async () => {
|
||||
const transport = { sendMail: vi.fn().mockResolvedValue({ messageId: "message-2" }) };
|
||||
const mailer = createMailer({ from: "portal@example.com", transport });
|
||||
|
||||
await mailer.sendApprovalNotice({ to: "editorial@example.com", editorialName: "Neue Redaktion" });
|
||||
|
||||
expect(transport.sendMail).toHaveBeenCalledWith({
|
||||
from: "portal@example.com",
|
||||
to: "editorial@example.com",
|
||||
subject: "Ihr Zugang zum Redaktionsportal ist freigegeben",
|
||||
text: expect.stringContaining("Neue Redaktion"),
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import "server-only";
|
||||
|
||||
import nodemailer from "nodemailer";
|
||||
|
||||
import { env } from "@/config/env";
|
||||
|
||||
export type MailMessage = {
|
||||
from: string;
|
||||
to: string;
|
||||
subject: string;
|
||||
text: string;
|
||||
};
|
||||
|
||||
export type MailTransport = {
|
||||
sendMail(message: MailMessage): Promise<unknown>;
|
||||
};
|
||||
|
||||
export type Mailer = {
|
||||
sendVerification(input: { to: string; verificationUrl: string }): Promise<void>;
|
||||
sendPasswordReset(input: { to: string; resetUrl: string }): Promise<void>;
|
||||
sendApprovalNotice(input: { to: string; editorialName: string }): Promise<void>;
|
||||
};
|
||||
|
||||
export function createMailer({ from, transport }: { from: string; transport: MailTransport }): Mailer {
|
||||
async function send(message: Omit<MailMessage, "from">): Promise<void> {
|
||||
await transport.sendMail({ from, ...message });
|
||||
}
|
||||
|
||||
return {
|
||||
async sendVerification({ to, verificationUrl }) {
|
||||
await send({
|
||||
to,
|
||||
subject: "Bitte bestätigen Sie Ihre E-Mail-Adresse",
|
||||
text: `Bitte bestätigen Sie Ihre E-Mail-Adresse für das Redaktionsportal:\n\n${verificationUrl}`,
|
||||
});
|
||||
},
|
||||
async sendPasswordReset({ to, resetUrl }) {
|
||||
await send({
|
||||
to,
|
||||
subject: "Passwort für das Redaktionsportal zurücksetzen",
|
||||
text: `Setzen Sie Ihr Passwort für das Redaktionsportal zurück:\n\n${resetUrl}`,
|
||||
});
|
||||
},
|
||||
async sendApprovalNotice({ to, editorialName }) {
|
||||
await send({
|
||||
to,
|
||||
subject: "Ihr Zugang zum Redaktionsportal ist freigegeben",
|
||||
text: `Der Zugang für ${editorialName} wurde freigegeben. Sie können sich jetzt im Redaktionsportal anmelden.`,
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const smtpTransport = nodemailer.createTransport({
|
||||
host: env.SMTP_HOST,
|
||||
port: env.SMTP_PORT,
|
||||
secure: env.SMTP_PORT === 465,
|
||||
auth: {
|
||||
user: env.SMTP_USER,
|
||||
pass: env.SMTP_PASSWORD,
|
||||
},
|
||||
});
|
||||
|
||||
export const mailer = createMailer({ from: env.SMTP_FROM, transport: smtpTransport });
|
||||
Reference in new issue
Block a user