Selbstregistrierung mit E-Mail-Bestätigung, standardmäßig aus (#36)
- POST /auth/register (nur wenn registration_enabled): Privat-/Geschäfts- kunde mit den vorhandenen Fachregeln, Passwort, Datenschutz-Zustimmung, Kundengrenze unter Sperre; Antwort immer 202 (keine Auskunft über bestehende Konten – diese bekommen nur eine Hinweis-Mail), Rate-Limit. - POST /auth/verify-email: Einmal-Token (24 h). Freischaltung je Einstellung automatisch oder durch Personal (Standard: Personal). - Verwaltung: Einstellung (Superadmin) + Freigabeliste unter Kunden, Freischalten/Ablehnen mit Audit und Mail. Seiten /registrieren und /email-bestaetigen, Link auf der Anmeldung nur wenn eingeschaltet. - Migration 042 (Einstellung, organizations.source, drei Mailvorlagen). Tests: aus, manuell/auto, Einmal-/Ablauf-Token, Enumeration, Fachregeln, Kundengrenze. Passkeys bleiben eigene spätere Aufgabe. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
441341ccef
commit
07d3c01bf4
12 changed files with 275 additions and 8 deletions
|
|
@ -15,7 +15,7 @@ export async function createInvitedUser(c: PoolConnection, u: { email: string; n
|
|||
}
|
||||
export async function createToken(c: PoolConnection | undefined, userId: string, purpose: 'invite' | 'password_reset' | 'verify_email'): Promise<string> {
|
||||
const token = randomToken(32);
|
||||
const hours = purpose === 'invite' ? INVITE_DAYS * 24 : 1;
|
||||
const hours = purpose === 'invite' ? INVITE_DAYS * 24 : purpose === 'verify_email' ? 24 : 1;
|
||||
await run('INSERT INTO user_tokens (id, user_id, purpose, token_hash, expires_at) VALUES (?,?,?,?, DATE_ADD(UTC_TIMESTAMP(3), INTERVAL ? HOUR))', [randomUUID(), userId, purpose, sha256(token), hours], c);
|
||||
return token;
|
||||
}
|
||||
|
|
@ -25,3 +25,5 @@ export const resetLink = (token: string): string => `${config.baseUrl}/passwort-
|
|||
export async function mailInvite(email: string, name: string, token: string): Promise<string> {
|
||||
return sendTemplateMail(email, 'invite', { name, inviteLink: inviteLink(token), validDays: String(INVITE_DAYS) });
|
||||
}
|
||||
/** Argon2id-Parameter für Passwörter (gleich in Anmeldung, Einladung, Registrierung). */
|
||||
export const ARGON = { memoryCost: 19456, timeCost: 2, parallelism: 1 };
|
||||
|
|
|
|||
|
|
@ -7,14 +7,16 @@ import { clientIp, requireAuth, requirePermission, IMPERSONATION_MINUTES } from
|
|||
import { badRequest, conflict, forbidden, notFound } from '../../core/errors.js';
|
||||
import { assertCustomerCapacity } from '../../core/license.js';
|
||||
import { canInOrg } from '../../core/policy.js';
|
||||
import { createInvitedUser, createToken, inviteLink, mailInvite } from '../../core/accounts.js';
|
||||
import { ARGON, createInvitedUser, createToken, inviteLink, mailInvite } from '../../core/accounts.js';
|
||||
import { enqueue } from '../../core/jobs.js';
|
||||
import { calculatePrice } from '@kc/platform/pricing';
|
||||
import { addMonths, consumerTerms } from '@kc/platform/contractterms';
|
||||
import { getConnector, loadInstance, syncInstance } from '@kc/connectors';
|
||||
import { ConnectorError, type ImportableCustomer } from '@kc/connector-sdk';
|
||||
import { AppError } from '../../core/errors.js';
|
||||
import { config } from '../../core/config.js';
|
||||
import { config, rl } from '../../core/config.js';
|
||||
import { sha256 } from '../../core/crypto.js';
|
||||
import { hash } from '@node-rs/argon2';
|
||||
import { sendTemplateMail } from '../../core/mail.js';
|
||||
import type { KcModule } from '../../core/module.js';
|
||||
import { enqueueCustomerSync } from '@kc/platform/customerSync';
|
||||
|
|
@ -106,6 +108,93 @@ export const customersModule: KcModule = {
|
|||
return { id: orgId, customerNumber: res.number, mail, inviteLink: mail === 'sent' ? undefined : inviteLink(res.inv.token) };
|
||||
});
|
||||
|
||||
// ---- Selbstregistrierung (#36) – nur wenn settings.registration_enabled = 'true' --------------------------
|
||||
const regSettings = async () => {
|
||||
const rows = await query("SELECT `key`, `value` FROM settings WHERE `key` IN ('registration_enabled','registration_approval')");
|
||||
const m = Object.fromEntries(rows.map((r) => [r.key, r.value]));
|
||||
return { enabled: m.registration_enabled === 'true', approval: (m.registration_approval === 'auto' ? 'auto' : 'manual') as 'auto' | 'manual' };
|
||||
};
|
||||
app.get('/auth/registration', async () => ({ enabled: (await regSettings()).enabled }));
|
||||
/** Antwortet immer gleich (202), egal ob die E-Mail schon existiert – keine Auskunft über bestehende Konten. */
|
||||
app.post('/auth/register', { config: rl(5, '10 minutes') }, async (req, reply) => {
|
||||
const rs = await regSettings();
|
||||
if (!rs.enabled) throw notFound();
|
||||
const b = z.object({
|
||||
type: z.enum(['private', 'business']), name: z.string().trim().min(2).max(200), contactName: z.string().trim().min(2).max(150).optional(),
|
||||
email, password: z.string().min(12).max(200), repeat: z.string(), vatId: z.string().trim().max(30).optional(), acceptPrivacy: z.literal(true),
|
||||
}).parse(req.body);
|
||||
if (b.password !== b.repeat) throw badRequest('Die Passwörter stimmen nicht überein', 'PASSWORD_MISMATCH');
|
||||
const vatId = normVat(b.vatId) ?? null;
|
||||
applyTypeRules(b.type, b.name, { vatId: b.type === 'business' ? vatId : (b.vatId ? vatId : null) });
|
||||
const existing = await one('SELECT id FROM users WHERE email = ?', [b.email]);
|
||||
if (existing) {
|
||||
await sendTemplateMail(b.email, 'registration_exists', { loginLink: `${config.baseUrl}/login`, resetLink: `${config.baseUrl}/passwort-vergessen` }).catch(() => undefined);
|
||||
await audit({ actorType: 'anonymous', action: 'customer.register', result: 'denied', errorClass: 'email_exists', correlationId: req.correlationId, ip: clientIp(req) });
|
||||
return reply.code(202).send({ status: 'check_mail' });
|
||||
}
|
||||
const orgId = randomUUID(); const userId = randomUUID(); const pw = await hash(b.password, ARGON);
|
||||
const contact = b.type === 'private' ? b.name : (b.contactName ?? b.name);
|
||||
const token = await tx(async (c) => {
|
||||
const cap = await assertCustomerCapacity(c); // Kundengrenze gilt auch hier
|
||||
if (!cap.allowed) throw forbidden('Eine Registrierung ist derzeit nicht möglich. Bitte wenden Sie sich an den Support.', 'REGISTRATION_UNAVAILABLE');
|
||||
const number = await nextCustomerNumber(c);
|
||||
await run("INSERT INTO organizations (id, customer_number, name, customer_type, source) VALUES (?,?,?,?, 'registration')", [orgId, number, b.name, b.type], c);
|
||||
await run('INSERT INTO billing_profiles (org_id, company, contact_name, country, vat_id, billing_email) VALUES (?,?,?,?,?,?)', [orgId, b.type === 'business' ? b.name : null, contact, 'DE', b.type === 'business' ? vatId : null, b.email], c);
|
||||
// Konto bleibt 'invited' (keine Anmeldung möglich), bis die E-Mail bestätigt und – je nach Regel – freigegeben ist
|
||||
await run("INSERT INTO users (id, email, name, password_hash, kind, status) VALUES (?,?,?,?, 'customer', 'invited')", [userId, b.email, contact, pw], c);
|
||||
await run("INSERT INTO memberships (org_id, user_id, role) VALUES (?,?,'owner')", [orgId, userId], c);
|
||||
return createToken(c, userId, 'verify_email');
|
||||
});
|
||||
await sendTemplateMail(b.email, 'verify_email', { name: contact, verifyLink: `${config.baseUrl}/email-bestaetigen?token=${encodeURIComponent(token)}`, validHours: '24' }).catch(() => undefined);
|
||||
await audit({ actorType: 'anonymous', orgId, action: 'customer.register', resourceType: 'organization', resourceId: orgId, correlationId: req.correlationId, ip: clientIp(req), after: { customerType: b.type } });
|
||||
return reply.code(202).send({ status: 'check_mail' });
|
||||
});
|
||||
app.post('/auth/verify-email', { config: rl(10, '10 minutes') }, async (req) => {
|
||||
const { token } = z.object({ token: z.string().min(20).max(200) }).parse(req.body);
|
||||
const rs = await regSettings();
|
||||
const res = await tx(async (c) => {
|
||||
const t = await one("SELECT id, user_id FROM user_tokens WHERE token_hash = ? AND purpose = 'verify_email' AND used_at IS NULL AND expires_at > UTC_TIMESTAMP(3) FOR UPDATE", [sha256(token)], c);
|
||||
if (!t) throw badRequest('Der Link ist ungültig oder abgelaufen. Bitte registrieren Sie sich erneut oder wenden Sie sich an den Support.', 'TOKEN_INVALID');
|
||||
await run('UPDATE user_tokens SET used_at = UTC_TIMESTAMP(3) WHERE id = ?', [t.id], c);
|
||||
await run("UPDATE users SET email_verified_at = UTC_TIMESTAMP(3), status = IF(? = 'auto', 'active', status) WHERE id = ?", [rs.approval, t.user_id], c);
|
||||
const m = await one("SELECT org_id FROM memberships WHERE user_id = ? AND role = 'owner'", [t.user_id], c);
|
||||
return { userId: t.user_id as string, orgId: m?.org_id as string | undefined };
|
||||
});
|
||||
await audit({ actorType: 'user', actorId: res.userId, orgId: res.orgId, action: 'customer.register.verified', resourceType: 'user', resourceId: res.userId, correlationId: req.correlationId, ip: clientIp(req), after: { approval: rs.approval } });
|
||||
if (rs.approval === 'manual') await enqueue('discord.notify', { event: 'customer.registered' }, { idempotencyKey: `customer.registered:${res.userId}`, correlationId: req.correlationId });
|
||||
return { status: rs.approval === 'auto' ? 'active' : 'pending_approval' };
|
||||
});
|
||||
app.get('/admin/registration-settings', async (req) => { requirePermission(req, 'customers.read'); return regSettings(); });
|
||||
app.put('/admin/registration-settings', async (req) => {
|
||||
const a = requirePermission(req, 'settings.write');
|
||||
const b = z.object({ enabled: z.boolean(), approval: z.enum(['manual', 'auto']) }).parse(req.body);
|
||||
await run("INSERT INTO settings (`key`, `value`) VALUES ('registration_enabled', ?), ('registration_approval', ?) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`)", [String(b.enabled), b.approval]);
|
||||
await audit({ actorType: 'user', actorId: a.user.id, action: 'settings.registration', resourceType: 'settings', resourceId: 'registration', correlationId: req.correlationId, ip: clientIp(req), after: b });
|
||||
return regSettings();
|
||||
});
|
||||
/** Bestätigte, noch nicht freigegebene Registrierungen (Freischaltung „manuell“). */
|
||||
app.get('/admin/registrations', async (req) => {
|
||||
requirePermission(req, 'customers.read');
|
||||
const rows = await query(`SELECT u.id AS user_id, u.email, u.name, u.email_verified_at, o.id AS org_id, o.name AS org_name, o.customer_number, o.customer_type
|
||||
FROM users u JOIN memberships m ON m.user_id = u.id AND m.role = 'owner' JOIN organizations o ON o.id = m.org_id
|
||||
WHERE o.source = 'registration' AND u.status = 'invited' AND u.email_verified_at IS NOT NULL ORDER BY u.email_verified_at`);
|
||||
return rows.map((r) => ({ userId: r.user_id, email: r.email, name: r.name, verifiedAt: r.email_verified_at, orgId: r.org_id, orgName: r.org_name, customerNumber: r.customer_number, customerType: r.customer_type }));
|
||||
});
|
||||
app.post('/admin/registrations/:userId/:decision', async (req) => {
|
||||
const a = requirePermission(req, 'customers.write');
|
||||
const { userId, decision } = z.object({ userId: z.string().uuid(), decision: z.enum(['approve', 'reject']) }).parse(req.params);
|
||||
const r = await tx(async (c) => {
|
||||
const u = await one("SELECT u.id, u.email, u.name, m.org_id FROM users u JOIN memberships m ON m.user_id = u.id AND m.role = 'owner' JOIN organizations o ON o.id = m.org_id AND o.source = 'registration' WHERE u.id = ? AND u.status = 'invited' AND u.email_verified_at IS NOT NULL FOR UPDATE", [userId], c);
|
||||
if (!u) throw notFound();
|
||||
if (decision === 'approve') await run("UPDATE users SET status = 'active' WHERE id = ?", [userId], c);
|
||||
else { await run("UPDATE users SET status = 'disabled' WHERE id = ?", [userId], c); await run("UPDATE organizations SET status = 'closed' WHERE id = ?", [u.org_id], c); }
|
||||
return u;
|
||||
});
|
||||
await audit({ actorType: 'user', actorId: a.user.id, orgId: r.org_id, action: `customer.register.${decision}`, resourceType: 'user', resourceId: userId, correlationId: req.correlationId, ip: clientIp(req) });
|
||||
if (decision === 'approve') await sendTemplateMail(r.email, 'registration_approved', { name: r.name, loginLink: `${config.baseUrl}/login` }).catch(() => undefined);
|
||||
return { ok: true };
|
||||
});
|
||||
|
||||
app.get('/admin/customers/:id', async (req) => {
|
||||
requirePermission(req, 'customers.read');
|
||||
const { id } = z.object({ id: z.string().uuid() }).parse(req.params);
|
||||
|
|
|
|||
|
|
@ -11,12 +11,11 @@ import { badRequest, conflict, forbidden, notFound, unauthorized } from '../../c
|
|||
import { assertStaffCapacity } from '../../core/license.js';
|
||||
import { decrypt, encrypt, sha256 } from '../../core/crypto.js';
|
||||
import { can, staffPermissions } from '../../core/policy.js';
|
||||
import { createInvitedUser, createToken, mailInvite, inviteLink, resetLink } from '../../core/accounts.js';
|
||||
import { createInvitedUser, createToken, mailInvite, inviteLink, resetLink, ARGON } from '../../core/accounts.js';
|
||||
import { sendTemplateMail } from '../../core/mail.js';
|
||||
import type { KcModule } from '../../core/module.js';
|
||||
import { enqueueSyncForOwner } from '@kc/platform/customerSync';
|
||||
|
||||
const ARGON = { memoryCost: 19456, timeCost: 2, parallelism: 1 };
|
||||
const MAX_FAILS = 5;
|
||||
const LOCK_MINUTES = 15;
|
||||
const password = z.string().min(12, 'Mindestens 12 Zeichen').max(200);
|
||||
|
|
|
|||
69
apps/api/test/registration.test.ts
Normal file
69
apps/api/test/registration.test.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
import { beforeAll, describe, expect, it } from 'vitest';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { buildApp } from '../src/server.js';
|
||||
import { one, run } from '../src/core/db.js';
|
||||
import { createToken } from '../src/core/accounts.js';
|
||||
import { setTestEdition } from '../src/core/license.js';
|
||||
import { call, code, login, makeUser } from './helpers.js';
|
||||
|
||||
let app: FastifyInstance; let admin: Awaited<ReturnType<typeof login>>['client'];
|
||||
const post = (url: string, payload: unknown) => app.inject({ method: 'POST', url: `/v1${url}`, payload: payload as never, headers: { origin: 'http://localhost:4101' } });
|
||||
const reg = (o: Record<string, unknown> = {}) => post('/auth/register', { type: 'private', name: 'Erika Muster', email: 'erika@reg.example', password: 'registrier-passwort-1', repeat: 'registrier-passwort-1', acceptPrivacy: true, ...o });
|
||||
const userBy = (email: string) => one('SELECT id, status, email_verified_at FROM users WHERE email = ?', [email]);
|
||||
const canLogin = async (email: string) => (await post('/auth/login', { email, password: 'registrier-passwort-1' })).statusCode === 200;
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await buildApp(); await app.ready();
|
||||
await makeUser({ email: 'reg-admin@example.com', kind: 'staff', staffRole: 'superadmin' }); admin = (await login(app, 'reg-admin@example.com')).client;
|
||||
const s = (await call(app, admin, 'POST', '/auth/mfa/setup')).json(); await call(app, admin, 'POST', '/auth/mfa/confirm', { code: code(s.secret) });
|
||||
});
|
||||
|
||||
describe('Selbstregistrierung (#36)', () => {
|
||||
it('standardmäßig aus: keine Registrierung möglich', async () => {
|
||||
expect((await app.inject({ method: 'GET', url: '/v1/auth/registration' })).json().enabled).toBe(false);
|
||||
expect((await reg()).statusCode).toBe(404);
|
||||
});
|
||||
it('Freischaltung durch Personal: Bestätigung allein erlaubt noch keine Anmeldung', async () => {
|
||||
expect((await call(app, admin, 'PUT', '/admin/registration-settings', { enabled: true, approval: 'manual' })).statusCode).toBe(200);
|
||||
expect((await reg()).statusCode).toBe(202);
|
||||
const u = (await userBy('erika@reg.example'))!; expect(u.status).toBe('invited'); expect(await canLogin('erika@reg.example')).toBe(false);
|
||||
expect((await one("SELECT o.source FROM organizations o JOIN memberships m ON m.org_id = o.id WHERE m.user_id = ?", [u.id]))!.source).toBe('registration');
|
||||
const t = await createToken(undefined, u.id, 'verify_email');
|
||||
expect((await post('/auth/verify-email', { token: t })).json().status).toBe('pending_approval');
|
||||
expect((await post('/auth/verify-email', { token: t })).statusCode).toBe(400); // Einmal-Token
|
||||
expect(await canLogin('erika@reg.example')).toBe(false);
|
||||
const list = (await call(app, admin, 'GET', '/admin/registrations')).json(); expect(list.map((r: any) => r.email)).toContain('erika@reg.example');
|
||||
expect((await call(app, admin, 'POST', `/admin/registrations/${u.id}/approve`)).statusCode).toBe(200);
|
||||
expect(await canLogin('erika@reg.example')).toBe(true);
|
||||
});
|
||||
it('keine Auskunft über bestehende Konten: gleiche Antwort, kein zweites Konto', async () => {
|
||||
const r = await reg(); expect(r.statusCode).toBe(202); expect(r.json()).toEqual({ status: 'check_mail' });
|
||||
expect(Number((await one("SELECT COUNT(*) AS n FROM users WHERE email = 'erika@reg.example'"))!.n)).toBe(1);
|
||||
});
|
||||
it('automatische Freischaltung, Ablehnung, abgelaufener Link', async () => {
|
||||
await call(app, admin, 'PUT', '/admin/registration-settings', { enabled: true, approval: 'auto' });
|
||||
await reg({ type: 'business', name: 'Muster GmbH', contactName: 'Max Muster', email: 'max@reg.example', vatId: 'DE 123.456.789' });
|
||||
const u = (await userBy('max@reg.example'))!;
|
||||
const t = await createToken(undefined, u.id, 'verify_email');
|
||||
expect((await post('/auth/verify-email', { token: t })).json().status).toBe('active'); expect(await canLogin('max@reg.example')).toBe(true);
|
||||
await reg({ email: 'old@reg.example' }); const o = (await userBy('old@reg.example'))!;
|
||||
const t2 = await createToken(undefined, o.id, 'verify_email'); await run("UPDATE user_tokens SET expires_at = DATE_SUB(UTC_TIMESTAMP(3), INTERVAL 1 MINUTE) WHERE user_id = ?", [o.id]);
|
||||
expect((await post('/auth/verify-email', { token: t2 })).statusCode).toBe(400);
|
||||
await call(app, admin, 'PUT', '/admin/registration-settings', { enabled: true, approval: 'manual' });
|
||||
await reg({ email: 'nein@reg.example' }); const n = (await userBy('nein@reg.example'))!;
|
||||
await post('/auth/verify-email', { token: await createToken(undefined, n.id, 'verify_email') });
|
||||
expect((await call(app, admin, 'POST', `/admin/registrations/${n.id}/reject`)).statusCode).toBe(200);
|
||||
expect((await userBy('nein@reg.example'))!.status).toBe('disabled');
|
||||
});
|
||||
it('Fachregeln und Kundengrenze gelten', async () => {
|
||||
expect((await reg({ email: 'p@reg.example', vatId: 'DE123456789' })).statusCode).toBe(400); // Privatkunde ohne USt-IdNr.
|
||||
expect((await reg({ email: 'b@reg.example', type: 'business', name: 'X AG', vatId: 'ungültig!' })).statusCode).toBe(400);
|
||||
expect((await reg({ email: 'w@reg.example', repeat: 'anders-passwort-12' })).statusCode).toBe(400);
|
||||
expect((await reg({ email: 'd@reg.example', acceptPrivacy: false })).statusCode).toBe(400);
|
||||
const cnt = Number((await one("SELECT COUNT(*) AS n FROM organizations WHERE status IN ('active','suspended')"))!.n);
|
||||
setTestEdition({ mode: 'licensed', features: [], customerLimit: cnt, staffLimit: null, reason: 'test' });
|
||||
try { const r = await reg({ email: 'voll@reg.example' }); expect(r.statusCode).toBe(403); expect(r.json().error.code).toBe('REGISTRATION_UNAVAILABLE'); }
|
||||
finally { setTestEdition(null); }
|
||||
expect((await call(app, admin, 'PUT', '/admin/registration-settings', { enabled: false, approval: 'manual' })).statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
|
|
@ -5,6 +5,30 @@ import { api, errMsg } from '@/lib/api';
|
|||
import { useSession } from '@/lib/session';
|
||||
import { Alert, Empty, Field, Status } from '@/components/ui';
|
||||
|
||||
interface Reg { userId: string; email: string; name: string; verifiedAt: string; orgId: string; orgName: string; customerNumber: string; customerType: string }
|
||||
/** Selbstregistrierung (#36): Einstellung (Superadmin) und Freigabeliste. Standard: aus, Freischaltung durch Personal. */
|
||||
function Registrierungen() {
|
||||
const { can } = useSession();
|
||||
const [cfg, setCfg] = useState<{ enabled: boolean; approval: 'manual' | 'auto' } | null>(null); const [regs, setRegs] = useState<Reg[]>([]); const [msg, setMsg] = useState<{ k: 'ok' | 'err'; t: string } | null>(null);
|
||||
const load = useCallback(() => { api<typeof cfg>('GET', '/admin/registration-settings').then(setCfg).catch(() => undefined); api<Reg[]>('GET', '/admin/registrations').then(setRegs).catch(() => undefined); }, []);
|
||||
useEffect(() => { load(); }, [load]);
|
||||
const save = async (next: { enabled: boolean; approval: 'manual' | 'auto' }) => { try { setCfg(await api('PUT', '/admin/registration-settings', next)); setMsg({ k: 'ok', t: 'Gespeichert.' }); } catch (x) { setMsg({ k: 'err', t: errMsg(x) }); } };
|
||||
const decide = async (r: Reg, d: 'approve' | 'reject') => { try { await api('POST', `/admin/registrations/${r.userId}/${d}`); setMsg({ k: 'ok', t: d === 'approve' ? `${r.orgName} freigeschaltet.` : `${r.orgName} abgelehnt.` }); load(); } catch (x) { setMsg({ k: 'err', t: errMsg(x) }); } };
|
||||
if (!cfg) return null;
|
||||
if (!cfg.enabled && regs.length === 0 && !can('settings.write')) return null;
|
||||
return (<div className="card"><h2>Selbstregistrierung</h2>
|
||||
{msg && <Alert kind={msg.k}>{msg.t}</Alert>}
|
||||
<p className="small muted">Status: {cfg.enabled ? 'eingeschaltet' : 'aus'} · Freischaltung: {cfg.approval === 'auto' ? 'automatisch nach E-Mail-Bestätigung' : 'durch das Personal'}</p>
|
||||
{can('settings.write') && <div className="row" style={{ gap: 16, flexWrap: 'wrap' }}>
|
||||
<label className="row" style={{ gap: 8 }}><input type="checkbox" checked={cfg.enabled} onChange={(e) => void save({ ...cfg, enabled: e.target.checked })} style={{ width: 20, minHeight: 20 }} />Registrierung über die Anmeldeseite erlauben</label>
|
||||
<label className="row" style={{ gap: 8 }}><input type="checkbox" checked={cfg.approval === 'auto'} onChange={(e) => void save({ ...cfg, approval: e.target.checked ? 'auto' : 'manual' })} style={{ width: 20, minHeight: 20 }} />Ohne Prüfung freischalten</label></div>}
|
||||
{regs.length > 0 && <div className="tablewrap"><table><thead><tr><th>Kunde</th><th>Art</th><th>E-Mail</th><th>Bestätigt</th><th></th></tr></thead><tbody>
|
||||
{regs.map((r) => <tr key={r.userId}><td>{r.orgName} <span className="muted small">({r.customerNumber})</span></td><td>{r.customerType === 'business' ? 'Geschäftskunde' : 'Privatkunde'}</td><td>{r.email}</td><td className="small">{new Date(r.verifiedAt).toLocaleString('de-DE', { dateStyle: 'short', timeStyle: 'short' })}</td>
|
||||
<td>{can('customers.write') && <div className="row" style={{ gap: 8 }}><button className="btn small primary" onClick={() => void decide(r, 'approve')}>Freischalten</button><button className="btn small danger" onClick={() => void decide(r, 'reject')}>Ablehnen</button></div>}</td></tr>)}
|
||||
</tbody></table></div>}
|
||||
</div>);
|
||||
}
|
||||
|
||||
interface Cust { id: string; customerNumber: string; name: string; customerType: 'private' | 'business'; status: string; city: string | null; billingEmail: string | null; members: number }
|
||||
export default function Kunden() {
|
||||
const { can } = useSession();
|
||||
|
|
@ -26,6 +50,7 @@ export default function Kunden() {
|
|||
}
|
||||
return (<>
|
||||
<div className="row between"><h1>Kunden</h1>{can('customers.write') && <div className="row"><Link className="btn" href="/admin/kunden/uebernahme">Aus Verbindung übernehmen</Link><button className="btn primary" onClick={() => { setOpen(!open); setCreated(null); }} aria-expanded={open}>Kunde anlegen</button></div>}</div>
|
||||
<Registrierungen />
|
||||
{err && <Alert kind="err">{err}</Alert>}
|
||||
{created && <Alert kind={created.mail === 'sent' ? 'ok' : 'warn'}>Kunde {created.customerNumber} angelegt. {created.mail === 'sent' ? 'Die Einladung wurde per E-Mail versendet.' : <>E-Mail-Versand ist nicht eingerichtet. Einladungslink (wird nur jetzt angezeigt): <code>{created.inviteLink}</code></>}</Alert>}
|
||||
{open && <form className="card" onSubmit={create}><h2>Neuer Kunde</h2>
|
||||
|
|
|
|||
23
apps/web/src/app/email-bestaetigen/page.tsx
Normal file
23
apps/web/src/app/email-bestaetigen/page.tsx
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
'use client';
|
||||
import { Suspense, useEffect, useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { api, errMsg } from '@/lib/api';
|
||||
import { Alert } from '@/components/ui';
|
||||
|
||||
function Bestaetigen() {
|
||||
const token = useSearchParams().get('token') ?? '';
|
||||
const [state, setState] = useState<{ k: 'ok' | 'err' | 'info'; t: string } | null>(null);
|
||||
useEffect(() => {
|
||||
if (!token) { setState({ k: 'err', t: 'Der Link ist unvollständig.' }); return; }
|
||||
api<{ status: 'active' | 'pending_approval' }>('POST', '/auth/verify-email', { token })
|
||||
.then((r) => setState(r.status === 'active' ? { k: 'ok', t: 'Danke! Ihre E-Mail-Adresse ist bestätigt. Sie können sich jetzt anmelden.' } : { k: 'info', t: 'Danke! Ihre E-Mail-Adresse ist bestätigt. Wir prüfen Ihre Registrierung und schalten Ihren Zugang zeitnah frei – Sie erhalten dann eine E-Mail.' }))
|
||||
.catch((x) => setState({ k: 'err', t: errMsg(x) }));
|
||||
}, [token]);
|
||||
return <>{state ? <Alert kind={state.k}>{state.t}</Alert> : <p className="muted" role="status">Wird bestätigt …</p>}</>;
|
||||
}
|
||||
export default function EmailBestaetigen() {
|
||||
return <main id="main" className="center"><div className="auth card"><h1>E-Mail bestätigen</h1>
|
||||
<Suspense fallback={<p className="muted" role="status">Wird geladen …</p>}><Bestaetigen /></Suspense>
|
||||
<p className="small" style={{ marginTop: 16 }}><Link href="/login">Zur Anmeldung</Link></p></div></main>;
|
||||
}
|
||||
|
|
@ -10,7 +10,8 @@ import { ThemeToggle } from '@/components/ThemeToggle';
|
|||
export default function Login() {
|
||||
const r = useRouter(); const { me, reload } = useSession();
|
||||
const [step, setStep] = useState<'pw' | 'mfa'>('pw');
|
||||
const [err, setErr] = useState(''); const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState(''); const [busy, setBusy] = useState(false); const [regOpen, setRegOpen] = useState(false);
|
||||
useEffect(() => { api<{ enabled: boolean }>('GET', '/auth/registration').then((r) => setRegOpen(r.enabled)).catch(() => undefined); }, []);
|
||||
useEffect(() => { if (me?.pendingMfa) setStep('mfa'); else if (me) r.replace('/dashboard'); }, [me, r]);
|
||||
|
||||
async function submit(e: FormEvent<HTMLFormElement>) {
|
||||
|
|
@ -40,7 +41,7 @@ export default function Login() {
|
|||
)}
|
||||
<button className="btn primary" disabled={busy} type="submit">{busy ? 'Bitte warten …' : step === 'pw' ? 'Anmelden' : 'Bestätigen'}</button>
|
||||
</form>
|
||||
{step === 'pw' && <p className="small" style={{ marginTop: 16 }}><Link href="/passwort-vergessen">Passwort vergessen?</Link></p>}
|
||||
{step === 'pw' && <p className="small" style={{ marginTop: 16 }}><Link href="/passwort-vergessen">Passwort vergessen?</Link>{regOpen && <> · <Link href="/registrieren">Neu hier? Registrieren</Link></>}</p>}
|
||||
</div></main>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
38
apps/web/src/app/registrieren/page.tsx
Normal file
38
apps/web/src/app/registrieren/page.tsx
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
'use client';
|
||||
import { useEffect, useState, type FormEvent } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { api, errMsg } from '@/lib/api';
|
||||
import { Alert, Field } from '@/components/ui';
|
||||
|
||||
/** Selbstregistrierung (#36) – nur sichtbar, wenn in der Verwaltung eingeschaltet. */
|
||||
export default function Registrieren() {
|
||||
const [enabled, setEnabled] = useState<boolean | null>(null); const [type, setType] = useState<'private' | 'business'>('private');
|
||||
const [done, setDone] = useState(false); const [err, setErr] = useState(''); const [busy, setBusy] = useState(false);
|
||||
useEffect(() => { api<{ enabled: boolean }>('GET', '/auth/registration').then((r) => setEnabled(r.enabled)).catch(() => setEnabled(false)); }, []);
|
||||
async function submit(e: FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault(); setErr(''); setBusy(true);
|
||||
const f = new FormData(e.currentTarget); const v = (k: string) => String(f.get(k) ?? '').trim() || undefined;
|
||||
try {
|
||||
await api('POST', '/auth/register', { type, name: v('name'), contactName: type === 'business' ? v('contactName') : undefined, email: v('email'), password: f.get('password'), repeat: f.get('repeat'), vatId: type === 'business' ? v('vatId') : undefined, acceptPrivacy: f.get('privacy') === 'on' });
|
||||
setDone(true);
|
||||
} catch (x) { setErr(errMsg(x)); } finally { setBusy(false); }
|
||||
}
|
||||
return <main id="main" className="center"><div className="auth card"><h1>Registrieren</h1>
|
||||
{enabled === null ? <p className="muted" role="status">Wird geladen …</p>
|
||||
: !enabled ? <Alert kind="info">Eine Selbstregistrierung ist derzeit nicht möglich. Bitte wenden Sie sich an uns, wir legen Ihren Zugang an.</Alert>
|
||||
: done ? <Alert kind="ok">Fast geschafft: Bitte prüfen Sie Ihr Postfach und bestätigen Sie Ihre E-Mail-Adresse über den Link in unserer Nachricht.</Alert>
|
||||
: <form onSubmit={submit}>
|
||||
{err && <Alert kind="err">{err}</Alert>}
|
||||
<fieldset style={{ border: 0, padding: 0, margin: '0 0 12px' }}><legend className="small">Kundenart</legend>
|
||||
<div className="row">{([['private', 'Privatkunde'], ['business', 'Geschäftskunde']] as const).map(([k, l]) => <label key={k} className="row"><input type="radio" name="ctype" checked={type === k} onChange={() => setType(k)} style={{ width: 20, minHeight: 20 }} />{l}</label>)}</div></fieldset>
|
||||
<Field id="name" label={type === 'business' ? 'Firmenname' : 'Vor- und Nachname'}><input id="name" name="name" required minLength={2} autoComplete={type === 'business' ? 'organization' : 'name'} /></Field>
|
||||
{type === 'business' && <><Field id="contactName" label="Ansprechpartner"><input id="contactName" name="contactName" autoComplete="name" /></Field>
|
||||
<Field id="vatId" label="USt-IdNr." hint="Optional, z. B. DE123456789"><input id="vatId" name="vatId" /></Field></>}
|
||||
<Field id="email" label="E-Mail"><input id="email" name="email" type="email" required autoComplete="email" /></Field>
|
||||
<Field id="password" label="Passwort" hint="Mindestens 12 Zeichen."><input id="password" name="password" type="password" minLength={12} required autoComplete="new-password" /></Field>
|
||||
<Field id="repeat" label="Passwort wiederholen"><input id="repeat" name="repeat" type="password" minLength={12} required autoComplete="new-password" /></Field>
|
||||
<label className="row small" style={{ gap: 8, margin: '8px 0 16px' }}><input type="checkbox" name="privacy" required style={{ width: 20, minHeight: 20 }} />Ich habe die Datenschutzhinweise gelesen und bin mit der Verarbeitung meiner Angaben zur Einrichtung des Zugangs einverstanden.</label>
|
||||
<button className="btn primary" type="submit" disabled={busy}>{busy ? 'Bitte warten …' : 'Registrieren'}</button>
|
||||
</form>}
|
||||
<p className="small" style={{ marginTop: 16 }}><Link href="/login">Zur Anmeldung</Link></p></div></main>;
|
||||
}
|
||||
|
|
@ -17,6 +17,7 @@ type Handler = (payload: any, job: JobMeta) => Promise<string | void>;
|
|||
const handlers: Record<string, Handler> = {
|
||||
'discord.notify': async (p) => {
|
||||
const text = p.event === 'customer.created' ? `Neuer Kunde angelegt: ${p.customerNumber}`
|
||||
: p.event === 'customer.registered' ? 'Neue Selbstregistrierung wartet auf Freigabe (Verwaltung → Kunden)'
|
||||
: p.event === 'backup.failed' ? `⚠ Backup fehlgeschlagen: ${p.detail ?? ''}`.trim()
|
||||
: p.event === 'backup.stale' ? `⚠ Kein aktuelles Backup: ${p.detail ?? ''}`.trim()
|
||||
: p.event === 'restoretest.failed' ? `⚠ Wiederherstellungstest fehlgeschlagen: ${p.detail ?? ''}`.trim()
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ Stand: 06.10.2026, aus `apps/web/src/app` (alle `page.tsx`). Sichtbarkeit richte
|
|||
- `/login` – Anmeldung, zweiter Schritt 2FA
|
||||
- `/passwort-vergessen`, `/passwort-reset` – Selbstbedienung per E-Mail-Link
|
||||
- `/einladung` – Einladung annehmen, Passwort festlegen
|
||||
- `/registrieren`, `/email-bestaetigen` – Selbstregistrierung mit E-Mail-Bestätigung (nur wenn eingeschaltet, #36)
|
||||
- `/vertrag-entscheidung` – „Vertrag behalten / kündigen“ aus der Erinnerungsmail (Einmal-Link)
|
||||
|
||||
## Kunde
|
||||
|
|
|
|||
|
|
@ -92,6 +92,7 @@ Annahmen: Angreifer von außen ohne Konto; Kunde, der fremde Daten sehen will; k
|
|||
| T17 | Wettlauf um letzte freie Plätze (Kunden/Personal) | Zeilensperre bis Commit | platform/license | `license.test.ts` (parallel) |
|
||||
| T18 | Rechnungsmanipulation nach Ausstellung | Statusprüfung unter Zeilensperre, Snapshots, Storno statt Änderung, Audit | invoices | `invoices.test.ts` (#95) |
|
||||
| T19 | Audit-Protokoll verfälschen | Hash-Kette, Trigger verbieten UPDATE/DELETE, Prüfung im Restore-Test | audit | `core.test.ts` „führt eine intakte Hash-Kette … erkennt eine eingeschleuste Fälschung“; täglicher Restore-Test prüft die Kette |
|
||||
| T21 | Selbstregistrierung: Konten ausspähen, Massenanlagen, fremde E-Mail | standardmäßig aus; Antwort immer 202 (bestehende Adresse bekommt nur eine Hinweis-Mail), Rate-Limit 5/10 min, Konto erst nach E-Mail-Bestätigung (Einmal-Token, 24 h) und – Standard – Freigabe durch Personal; Kundengrenze gilt | customers | `registration.test.ts` |
|
||||
| T20 | Datenverlust / Erpressung | Verschlüsselte Backups, externes Ziel, automatischer Restore-Test, Alarm | backup | `backup*.test.ts`, täglicher Restore-Test |
|
||||
|
||||
**Beispielpayloads** in Tests und Doku enthalten nie echte Schlüssel (Dummy-`KC_SECRET_KEY`, generierte Testschlüssel).
|
||||
|
|
@ -99,5 +100,5 @@ Annahmen: Angreifer von außen ohne Konto; Kunde, der fremde Daten sehen will; k
|
|||
## 4. Offene Punkte
|
||||
|
||||
- T9: Allowlist für Connector-Ziele (Entscheidung: welche Hosts sind erlaubt?).
|
||||
- Passkeys (#36/#23) und Selbstregistrierung (#36) sind noch nicht umgesetzt; bei Einführung Enumeration-Schutz und Verifizierung ergänzen.
|
||||
- Passkeys (#23) sind noch nicht umgesetzt. Selbstregistrierung ist vorbereitet und aus – vor dem Einschalten Pflichtfelder/Freischaltungsregel bestätigen (#36).
|
||||
- Modulmatrix der Installationslizenz (#113) → dann in API und Worker durchsetzen (#116).
|
||||
|
|
|
|||
18
migrations/042_self_registration.sql
Normal file
18
migrations/042_self_registration.sql
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
-- Selbstregistrierung (#36) – bleibt AUS, bis Björn Pflichtfelder und Freischaltungsregel bestätigt
|
||||
-- (settings.registration_enabled = 'false' seit 001). registration_approval: 'manual' (Personal gibt frei, Standard)
|
||||
-- oder 'auto' (nach E-Mail-Bestätigung sofort aktiv).
|
||||
INSERT INTO settings (`key`, `value`) VALUES ('registration_approval', 'manual') ON DUPLICATE KEY UPDATE `key` = `key`;
|
||||
ALTER TABLE organizations ADD COLUMN source ENUM('staff','import','registration') NOT NULL DEFAULT 'staff' AFTER customer_type;
|
||||
INSERT INTO mail_templates (`key`, name, trigger_text, category, variables_json, subject, body) VALUES
|
||||
('verify_email', 'E-Mail-Adresse bestätigen (Registrierung)', 'Nach einer Selbstregistrierung (nur wenn eingeschaltet).', 'kundencenter',
|
||||
JSON_ARRAY('name', 'verifyLink', 'validHours'),
|
||||
'Bitte bestätigen Sie Ihre E-Mail-Adresse',
|
||||
'Hallo {{name}},\n\nvielen Dank für Ihre Registrierung im Kundencenter. Bitte bestätigen Sie Ihre E-Mail-Adresse über den folgenden Link (gültig {{validHours}} Stunden):\n\n{{verifyLink}}\n\nFalls Sie sich nicht registriert haben, können Sie diese Nachricht ignorieren.\n'),
|
||||
('registration_exists', 'Registrierung mit bereits bekannter E-Mail', 'Jemand hat sich mit einer E-Mail registriert, zu der schon ein Konto besteht (keine Auskunft auf der Webseite).', 'kundencenter',
|
||||
JSON_ARRAY('loginLink', 'resetLink'),
|
||||
'Ihr Kundencenter-Zugang',
|
||||
'Hallo,\n\nfür diese E-Mail-Adresse gibt es bereits einen Zugang zum Kundencenter. Melden Sie sich einfach an:\n\n{{loginLink}}\n\nPasswort vergessen? Hier können Sie ein neues festlegen:\n\n{{resetLink}}\n\nFalls Sie das nicht waren, können Sie diese Nachricht ignorieren.\n'),
|
||||
('registration_approved', 'Registrierung freigeschaltet', 'Personal hat eine Selbstregistrierung freigegeben (Freischaltung „manuell“).', 'kundencenter',
|
||||
JSON_ARRAY('name', 'loginLink'),
|
||||
'Ihr Kundencenter-Zugang ist freigeschaltet',
|
||||
'Hallo {{name}},\n\nIhr Zugang zum Kundencenter wurde freigeschaltet. Sie können sich jetzt anmelden:\n\n{{loginLink}}\n');
|
||||
Loading…
Add table
Add a link
Reference in a new issue