feat: 2FA, Passwortrichtlinie und wiederherstellbares JSON-Backup

Zwei-Faktor per TOTP mit zehn Einmal-Wiederherstellungscodes. Der
Zwischenzustand "Passwort stimmt, Code fehlt" haengt an der vorhandenen
Sitzungstabelle (pending_2fa, zehn Minuten Laufzeit) und gilt nirgends als
angemeldet; nach dem Code wird das Cookie getauscht statt weiterverwendet.
Der Wiederverwendungsschutz merkt sich das tatsaechlich getroffene
Zeitfenster, nicht die aktuelle Uhrzeit - sonst liesse sich ein Code aus dem
naechsten Fenster gleich darauf nochmal einloesen.

Passwortrichtlinie (Laenge, Zeichenklassen, MFA-Pflicht) in der neuen
globalen Tabelle app_settings, durchgesetzt beim Anlegen, Zuruecksetzen und
Aendern von Passwoertern. Bestehende Passwoerter lassen sich nicht gegen eine
neue Richtlinie pruefen - der Hash gibt nichts her. Beim Anmelden liegt das
Passwort aber kurz im Klartext vor: dort wird geprueft und bei Verstoss ein
Wechsel verlangt, mit passendem Grund fuer den Hinweistext.

Nebenbei geschlossen: must_change_password war bisher nur im Frontend
erzwungen, wer die API direkt ansprach kam vorbei. enforce_account_state
haengt jetzt am /api-Sammelrouter und laesst nur noch durch, was man zum
Erfuellen der Pflicht braucht.

Das JSON-Backup liess sich bisher grundsaetzlich nicht zurueckladen: keine
Version, Kategorien nur ueber mehrdeutige Namen, sieben Tabellen fehlten.
Daneben steht nun ein Format v2, das Beziehungen ueber lokale IDs abbildet,
je Benutzer oder systemweit. Zurueckgeladen wird nach einer Pruefansicht,
wahlweise ersetzend oder ergaenzend; vor dem Ersetzen legt der Server einen
Schnappschuss der Datenbank an. Der alte Ansichts-Export bleibt fuer
Tabellenkalkulationen bestehen und wird beim Hochladen ausdruecklich
abgewiesen, statt halb zu raten.

Frontend: wiederverwendbares Passwortfeld mit Augensymbol, animierte
Anforderungsliste, 2FA-Seite, Admin-Karte fuer die Richtlinie und Karte zum
Zurueckladen. Neue Bewegung ist in prefers-reduced-motion hinterlegt; Secret
und Codes sind markierbar, sonst verhinderte das globale user-select das
Kopieren.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Scarriffle
2026-08-20 10:11:22 +02:00
co-authored by Claude Opus 5
parent 1d5b23c127
commit 7fc8763d57
40 changed files with 3539 additions and 117 deletions
+33 -13
View File
@@ -1,4 +1,4 @@
import { useState } from "react";
import { useEffect, useState } from "react";
import { Navigate, useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useAuth } from "../auth";
@@ -6,6 +6,9 @@ import { api, ApiError } from "../api";
import { useToast } from "../toast";
import BrandMark from "../components/BrandMark";
import Icon from "../components/Icon";
import PasswordInput from "../components/PasswordInput";
import PasswordRules from "../components/PasswordRules";
import { DEFAULT_POLICY, meetsPolicy } from "../passwordPolicy";
export default function ChangePassword() {
const { user, aktualisieren } = useAuth();
@@ -15,11 +18,21 @@ export default function ChangePassword() {
const [current, setCurrent] = useState("");
const [next, setNext] = useState("");
const [repeat, setRepeat] = useState("");
const [policy, setPolicy] = useState(DEFAULT_POLICY);
const [fehler, setFehler] = useState(null);
const [busy, setBusy] = useState(false);
useEffect(() => {
// Fällt der Abruf aus, bleibt die Vorgabe stehen – verbindlich prüft
// ohnehin der Server, hier geht es nur um die Anzeige.
api.getPolicy().then(setPolicy).catch(() => {});
}, []);
if (!user) return <Navigate to="/login" replace />;
const forced = user.must_change_password;
const wegenRichtlinie = user.must_change_password_reason === "policy";
const regelnErfuellt = meetsPolicy(policy, next, t);
const bereit = regelnErfuellt && next === repeat && current.length > 0;
async function onSubmit(e) {
e.preventDefault();
@@ -49,7 +62,7 @@ export default function ChangePassword() {
{forced && (
<div className="alert" style={{ marginBottom: "var(--sp-3)" }}>
<Icon name="key" size={16} />
<span>{t("changepw.forcedHint")}</span>
<span>{wegenRichtlinie ? t("changepw.policyHint") : t("changepw.forcedHint")}</span>
</div>
)}
{fehler && (
@@ -59,24 +72,31 @@ export default function ChangePassword() {
</div>
)}
<label>
<label className="field">
<span>{t("changepw.current")}</span>
<input type="password" autoComplete="current-password" value={current}
onChange={(e) => setCurrent(e.target.value)} required />
<PasswordInput value={current} onChange={setCurrent}
autoComplete="current-password" required />
</label>
<label>
<label className="field">
<span>{t("changepw.new")}</span>
<input type="password" autoComplete="new-password" value={next}
onChange={(e) => setNext(e.target.value)} required />
<PasswordInput value={next} onChange={setNext}
autoComplete="new-password" required />
</label>
<label>
<PasswordRules policy={policy} value={next} />
<label className="field" style={{ marginTop: "var(--sp-3)" }}>
<span>{t("changepw.repeat")}</span>
<input type="password" autoComplete="new-password" value={repeat}
onChange={(e) => setRepeat(e.target.value)} required />
<PasswordInput value={repeat} onChange={setRepeat}
autoComplete="new-password" required />
</label>
{repeat && next !== repeat && (
<span className="hint-danger">
<Icon name="alert" size={12} />
{t("changepw.mismatch")}
</span>
)}
<button className="btn primary" type="submit" disabled={busy}
style={{ width: "100%", marginTop: "var(--sp-2)" }}>
<button className="btn primary" type="submit" disabled={busy || !bereit}
style={{ width: "100%", marginTop: "var(--sp-3)" }}>
{busy ? t("common.loading") : t("changepw.submit")}
</button>
</form>
+91 -18
View File
@@ -5,24 +5,33 @@ import { useAuth } from "../auth";
import { ApiError } from "../api";
import BrandMark from "../components/BrandMark";
import Icon from "../components/Icon";
import PasswordInput from "../components/PasswordInput";
export default function Login() {
const { login, abgelaufen } = useAuth();
const { login, verifyTwoFactor, abgelaufen } = useAuth();
const { t } = useTranslation();
const navigate = useNavigate();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [zeigePw, setZeigePw] = useState(false);
const [fehler, setFehler] = useState(null);
const [busy, setBusy] = useState(false);
// Zweiter Schritt: erst gesetzt, wenn der Server nach dem Code fragt.
const [zweiterSchritt, setZweiterSchritt] = useState(false);
const [code, setCode] = useState("");
const [wiederherstellung, setWiederherstellung] = useState(false);
async function onSubmit(e) {
e.preventDefault();
setFehler(null);
setBusy(true);
try {
await login(username, password);
navigate("/");
const res = await login(username, password);
if (res.status === "2fa_required") {
setZweiterSchritt(true);
setPassword("");
} else {
navigate("/");
}
} catch (err) {
if (err instanceof ApiError && err.status === 401) setFehler(t("login.error"));
else setFehler(err.message || t("server.unreachable"));
@@ -31,6 +40,81 @@ export default function Login() {
}
}
async function onVerify(e) {
e.preventDefault();
setFehler(null);
setBusy(true);
try {
await verifyTwoFactor(code.trim(), wiederherstellung);
navigate("/");
} catch (err) {
setFehler(err.message || t("server.unreachable"));
setCode("");
} finally {
setBusy(false);
}
}
function zurueck() {
// Das Zwischen-Cookie läuft von allein ab; für den Neustart genügt es,
// wieder das Anmeldeformular zu zeigen.
setZweiterSchritt(false);
setCode("");
setWiederherstellung(false);
setFehler(null);
}
const meldung = fehler && (
<div className="alert error" style={{ marginBottom: "var(--sp-3)" }}>
<Icon name="alert" size={16} />
<span>{fehler}</span>
</div>
);
if (zweiterSchritt) {
return (
<div className="auth-screen">
<form className="card auth-card" onSubmit={onVerify}>
<BrandMark size={40} />
<p className="muted" style={{ textAlign: "center", marginTop: 0 }}>
{wiederherstellung ? t("twofactor.recoveryHint") : t("twofactor.codeHint")}
</p>
{meldung}
<label className="field">
<span>{wiederherstellung ? t("twofactor.recoveryCode") : t("twofactor.code")}</span>
{/* eslint-disable-next-line jsx-a11y/no-autofocus */}
<input
autoFocus
value={code}
onChange={(e) => setCode(e.target.value)}
required
autoComplete="one-time-code"
inputMode={wiederherstellung ? "text" : "numeric"}
maxLength={wiederherstellung ? 32 : 6}
placeholder={wiederherstellung ? "XXXXX-XXXXX" : "123456"}
/>
</label>
<button className="btn primary" type="submit" disabled={busy}
style={{ width: "100%", marginTop: "var(--sp-3)" }}>
{busy ? t("common.loading") : t("twofactor.verify")}
</button>
<div className="btn-pair" style={{ marginTop: "var(--sp-3)" }}>
<button type="button" className="btn sm ghost"
onClick={() => { setWiederherstellung((v) => !v); setCode(""); setFehler(null); }}>
{wiederherstellung ? t("twofactor.useApp") : t("twofactor.useRecovery")}
</button>
<button type="button" className="btn sm ghost" onClick={zurueck}>
{t("common.cancel")}
</button>
</div>
</form>
</div>
);
}
return (
<div className="auth-screen">
<form className="card auth-card" onSubmit={onSubmit}>
@@ -43,12 +127,7 @@ export default function Login() {
<span>{t("login.expired")}</span>
</div>
)}
{fehler && (
<div className="alert error" style={{ marginBottom: "var(--sp-3)" }}>
<Icon name="alert" size={16} />
<span>{fehler}</span>
</div>
)}
{meldung}
<label className="field">
<span>{t("login.username")}</span>
@@ -59,14 +138,8 @@ export default function Login() {
<label className="field">
<span>{t("login.password")}</span>
<div className="input-with-button">
<input type={zeigePw ? "text" : "password"} autoComplete="current-password"
value={password} onChange={(e) => setPassword(e.target.value)} required />
<button type="button" className="btn-icon" onClick={() => setZeigePw((v) => !v)}
title={zeigePw ? t("common.close") : ""} tabIndex={-1}>
<Icon name={zeigePw ? "eye-off" : "eye"} size={17} />
</button>
</div>
<PasswordInput value={password} onChange={setPassword}
autoComplete="current-password" required />
</label>
<button className="btn primary" type="submit" disabled={busy}
+37 -5
View File
@@ -1,10 +1,13 @@
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useSettings } from "../settings";
import { useAuth } from "../auth";
import { useToast } from "../toast";
import { api } from "../api";
import Icon from "../components/Icon";
import PolicyCard from "./settings/PolicyCard";
import RestoreCard from "./settings/RestoreCard";
export default function Settings() {
const { t } = useTranslation();
@@ -116,9 +119,26 @@ export default function Settings() {
<p className="muted small" style={{ marginTop: -8 }}>{t("settings.budgetStartDayHint")}</p>
</div>
<div className="card" style={{ maxWidth: 520, marginTop: "var(--sp-4)" }}>
<h2 style={{ display: "flex", alignItems: "center", gap: "var(--sp-2)", marginTop: 0 }}>
<Icon name="shield" size={18} /> {t("settings.security")}
</h2>
<p className="muted small">{t("settings.securityHint")}</p>
<Link className="btn" to="/zwei-faktor">
<Icon name="smartphone" size={15} /> {t("settings.twoFactor")}
</Link>
</div>
{isAdmin && <PolicyCard />}
<div className="card" style={{ maxWidth: 520, marginTop: "var(--sp-4)" }}>
<h2>{t("settings.backup")}</h2>
<p className="muted small">{t("settings.exportHint")}</p>
<p className="muted small">{t("settings.backupHint")}</p>
<button className="btn primary" onClick={() => dl(api.exportBackupJson)}>
<Icon name="download" size={15} /> {t("settings.exportBackup")}
</button>
<p className="muted small" style={{ marginTop: "var(--sp-4)" }}>{t("settings.exportHint")}</p>
<div className="field-inline" style={{ flexWrap: "wrap" }}>
<button className="btn" onClick={() => dl(api.exportTransactionsCsv)}>
<Icon name="download" size={15} /> {t("settings.exportTxnCsv")}
@@ -130,15 +150,27 @@ export default function Settings() {
<Icon name="download" size={15} /> {t("settings.exportAll")}
</button>
</div>
{isAdmin && (
<>
<p className="muted small" style={{ marginTop: "var(--sp-3)" }}>{t("settings.dbBackupHint")}</p>
<button className="btn primary" onClick={() => dl(api.downloadDbBackup)}>
<Icon name="download" size={15} /> {t("settings.dbBackup")}
</button>
<p className="muted small" style={{ marginTop: "var(--sp-4)" }}>{t("settings.dbBackupHint")}</p>
<div className="field-inline" style={{ flexWrap: "wrap" }}>
<button className="btn" onClick={() => dl(api.downloadDbBackup)}>
<Icon name="download" size={15} /> {t("settings.dbBackup")}
</button>
<button className="btn" onClick={() => dl(api.exportSystemBackupJson)}>
<Icon name="download" size={15} /> {t("settings.systemBackup")}
</button>
</div>
<div className="alert warn" style={{ marginTop: "var(--sp-3)" }}>
<Icon name="alert" size={16} />
<span>{t("settings.systemBackupWarning")}</span>
</div>
</>
)}
</div>
<RestoreCard />
</div>
);
}
+245
View File
@@ -0,0 +1,245 @@
import { useEffect, useState } from "react";
import { Navigate, useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useAuth } from "../auth";
import { api } from "../api";
import { useToast } from "../toast";
import { useConfirm } from "../confirm";
import Icon from "../components/Icon";
import PasswordInput from "../components/PasswordInput";
/** Codeliste als Textdatei sichern – Zwischenablage ist nicht überall erlaubt. */
function codesSichern(codes, benutzer) {
const inhalt =
`Certain Finance – Wiederherstellungscodes für ${benutzer}\n` +
`Jeder Code funktioniert genau einmal. Sicher aufbewahren.\n\n` +
codes.join("\n") + "\n";
const url = URL.createObjectURL(new Blob([inhalt], { type: "text/plain;charset=utf-8" }));
const link = document.createElement("a");
link.href = url;
link.download = `certain-finance-wiederherstellungscodes_${benutzer}.txt`;
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
}
/** Anzeige der frisch erzeugten Codes – sie sind danach nicht mehr abrufbar. */
function CodeListe({ codes, benutzer, onFertig }) {
const { t } = useTranslation();
const toast = useToast();
async function kopieren() {
try {
await navigator.clipboard.writeText(codes.join("\n"));
toast(t("twofactor.copied"));
} catch {
// Ohne sicheren Kontext (http) gibt es keine Zwischenablage – dann
// bleibt der Download, und markieren geht ohnehin.
codesSichern(codes, benutzer);
}
}
return (
<div className="card" style={{ maxWidth: 520, marginTop: "var(--sp-4)", borderColor: "var(--warn)" }}>
<h2 style={{ marginTop: 0 }}>{t("twofactor.codesTitle")}</h2>
<p className="muted small">{t("twofactor.codesHint")}</p>
<div className="tfa-codes selectable">
{codes.map((c) => <span key={c}>{c}</span>)}
</div>
<div className="btn-pair">
<button className="btn" onClick={kopieren}>
<Icon name="copy" size={15} /> {t("twofactor.copy")}
</button>
<button className="btn" onClick={() => codesSichern(codes, benutzer)}>
<Icon name="download" size={15} /> {t("twofactor.download")}
</button>
<button className="btn primary" onClick={onFertig}>{t("twofactor.codesSaved")}</button>
</div>
</div>
);
}
export default function TwoFactor() {
const { user, aktualisieren } = useAuth();
const { t } = useTranslation();
const toast = useToast();
const confirm = useConfirm();
const navigate = useNavigate();
const [status, setStatus] = useState(null);
const [policy, setPolicy] = useState(null);
const [setup, setSetup] = useState(null); // { secret, otpauth_uri, qr_png }
const [code, setCode] = useState("");
const [codes, setCodes] = useState(null); // frisch erzeugte Wiederherstellungscodes
const [fehler, setFehler] = useState(null);
const [busy, setBusy] = useState(false);
async function laden() {
try {
const [s, p] = await Promise.all([api.twoFactorStatus(), api.getPolicy()]);
setStatus(s);
setPolicy(p);
} catch (err) {
setFehler(err.message);
}
}
useEffect(() => { laden(); }, []);
if (!user) return <Navigate to="/login" replace />;
// Erst Passwort wechseln, dann zweiter Faktor – dieselbe Reihenfolge, die
// der Server erzwingt.
if (user.must_change_password) return <Navigate to="/passwort-aendern" replace />;
const pflicht = Boolean(policy?.mfa_required);
const erzwungen = pflicht && !status?.enabled;
async function starten() {
setFehler(null);
setBusy(true);
try {
setSetup(await api.twoFactorSetup());
} catch (err) {
setFehler(err.message);
} finally {
setBusy(false);
}
}
async function aktivieren(e) {
e.preventDefault();
setFehler(null);
setBusy(true);
try {
const res = await api.twoFactorActivate(code.trim());
setCodes(res.codes);
setSetup(null);
setCode("");
// Die Sperre „MFA einrichten" fällt damit weg – Benutzer neu laden.
aktualisieren(await api.me());
await laden();
} catch (err) {
setFehler(err.message);
} finally {
setBusy(false);
}
}
async function abschalten() {
const passwort = await confirm({
title: t("twofactor.disableTitle"),
message: t("twofactor.disableHint"),
confirmLabel: t("twofactor.disable"),
danger: true,
prompt: true,
inputType: "password",
});
if (!passwort) return;
try {
aktualisieren(await api.twoFactorDisable(passwort));
toast(t("twofactor.disabled"));
await laden();
} catch (err) {
setFehler(err.message);
}
}
async function codesErneuern() {
const passwort = await confirm({
title: t("twofactor.newCodesTitle"),
message: t("twofactor.newCodesHint"),
confirmLabel: t("twofactor.newCodes"),
prompt: true,
inputType: "password",
});
if (!passwort) return;
try {
const res = await api.newRecoveryCodes(passwort);
setCodes(res.codes);
await laden();
} catch (err) {
setFehler(err.message);
}
}
return (
<>
<h1>{t("twofactor.title")}</h1>
{fehler && (
<div className="alert error" style={{ maxWidth: 520, marginBottom: "var(--sp-4)" }}>
<Icon name="alert" size={16} />
<span>{fehler}</span>
</div>
)}
{erzwungen && (
<div className="alert warn" style={{ maxWidth: 520, marginBottom: "var(--sp-4)" }}>
<Icon name="shield" size={16} />
<span>{t("twofactor.requiredHint")}</span>
</div>
)}
<div className="card" style={{ maxWidth: 520 }}>
<h2 style={{ marginTop: 0, display: "flex", alignItems: "center", gap: "var(--sp-2)" }}>
<Icon name="shield" size={18} />
{status?.enabled ? t("twofactor.on") : t("twofactor.off")}
</h2>
<p className="muted small">{t("twofactor.intro")}</p>
{status?.enabled ? (
<>
<p className="small">
{t("twofactor.codesLeft", { n: status.recovery_codes_left })}
</p>
<div className="btn-pair">
<button className="btn" onClick={codesErneuern}>
<Icon name="refresh-ccw" size={15} /> {t("twofactor.newCodes")}
</button>
{!pflicht && (
<button className="btn danger" onClick={abschalten}>
{t("twofactor.disable")}
</button>
)}
</div>
</>
) : setup ? (
<form onSubmit={aktivieren}>
<p className="small">{t("twofactor.scan")}</p>
<img className="tfa-qr" src={setup.qr_png} alt={t("twofactor.qrAlt")} />
<p className="muted small" style={{ marginTop: "var(--sp-3)" }}>
{t("twofactor.manual")}
</p>
<code className="tfa-secret selectable">{setup.secret}</code>
<label className="field" style={{ marginTop: "var(--sp-4)" }}>
<span>{t("twofactor.code")}</span>
<input value={code} onChange={(e) => setCode(e.target.value)} required
inputMode="numeric" maxLength={6} autoComplete="one-time-code"
placeholder="123456" />
</label>
<div className="btn-pair" style={{ marginTop: "var(--sp-3)" }}>
<button className="btn primary" type="submit" disabled={busy}>
{busy ? t("common.loading") : t("twofactor.activate")}
</button>
<button className="btn ghost" type="button" onClick={() => { setSetup(null); setCode(""); }}>
{t("common.cancel")}
</button>
</div>
</form>
) : (
<button className="btn primary" onClick={starten} disabled={busy}>
<Icon name="smartphone" size={15} /> {t("twofactor.start")}
</button>
)}
</div>
{codes && (
<CodeListe
codes={codes}
benutzer={user.username}
onFertig={() => { setCodes(null); if (erzwungen) navigate("/"); }}
/>
)}
</>
);
}
+46 -12
View File
@@ -6,13 +6,8 @@ import { useConfirm } from "../confirm";
import { useToast } from "../toast";
import Icon from "../components/Icon";
import DataTable from "../components/DataTable";
function randomPassword(len = 12) {
const chars = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789";
const arr = new Uint32Array(len);
crypto.getRandomValues(arr);
return Array.from(arr, (n) => chars[n % chars.length]).join("");
}
import PasswordRules from "../components/PasswordRules";
import { DEFAULT_POLICY, meetsPolicy, randomPassword } from "../passwordPolicy";
export default function Users() {
const { t } = useTranslation();
@@ -21,6 +16,7 @@ export default function Users() {
const toast = useToast();
const [users, setUsers] = useState([]);
const [policy, setPolicy] = useState(DEFAULT_POLICY);
const [form, setForm] = useState({ username: "", display_name: "", password: "", role: "user" });
const [fehler, setFehler] = useState(null);
const [busy, setBusy] = useState(false);
@@ -35,6 +31,8 @@ export default function Users() {
useEffect(() => {
laden();
// Die Richtlinie bestimmt, was das erzeugte Temporär-Passwort erfüllen muss.
api.getPolicy().then(setPolicy).catch(() => {});
}, []);
async function anlegen(e) {
@@ -63,13 +61,31 @@ export default function Users() {
title: t("users.resetPassword"),
message: u.username,
prompt: true,
defaultValue: randomPassword(),
defaultValue: randomPassword(policy),
confirmLabel: t("common.save"),
});
if (!neu) return;
try {
await api.updateUser(u.id, { password: neu });
toast(t("settings.saved"));
laden();
} catch (err) {
toast(err.message, "error");
}
}
async function zweiFaktorZuruecksetzen(u) {
const ok = await confirm({
title: t("users.resetTwoFactor"),
message: t("users.resetTwoFactorConfirm", { name: u.username }),
confirmLabel: t("users.resetTwoFactor"),
danger: true,
});
if (!ok) return;
try {
await api.resetUserTwoFactor(u.id);
toast(t("users.twoFactorReset"));
laden();
} catch (err) {
toast(err.message, "error");
}
@@ -123,12 +139,26 @@ export default function Users() {
),
},
{
key: "actions", header: t("common.actions"), width: 132, fixed: true,
key: "twofactor", header: t("users.twoFactor"), width: 110,
filterText: (u) => (u.totp_enabled ? t("twofactor.on") : t("twofactor.off")),
render: (u) => (
<span className={`badge ${u.totp_enabled ? "ok" : ""}`}>
{u.totp_enabled ? t("twofactor.on") : t("twofactor.off")}
</span>
),
},
{
key: "actions", header: t("common.actions"), width: 168, fixed: true,
render: (u) => (
<div className="nowrap" style={{ textAlign: "right" }}>
<button className="btn sm ghost" title={t("users.resetPassword")} onClick={() => passwortZuruecksetzen(u)}>
<Icon name="key" size={15} />
</button>
{u.totp_enabled && (
<button className="btn sm ghost" title={t("users.resetTwoFactor")} onClick={() => zweiFaktorZuruecksetzen(u)}>
<Icon name="shield" size={15} />
</button>
)}
{u.id !== self?.id && (
<>
<button className="btn sm ghost" title={u.is_active ? t("users.inactive") : t("users.active")} onClick={() => aktivUmschalten(u)}>
@@ -142,8 +172,9 @@ export default function Users() {
</div>
),
},
// policy muss mit hinein: das erzeugte Vorschlagspasswort richtet sich danach.
// eslint-disable-next-line react-hooks/exhaustive-deps
], [t, self]);
], [t, self, policy]);
return (
<div>
@@ -174,10 +205,12 @@ export default function Users() {
<span>{t("users.password")}</span>
<div className="input-with-button">
<input value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} required />
<button type="button" className="btn sm" onClick={() => setForm({ ...form, password: randomPassword() })}>
<button type="button" className="btn sm" title={t("users.generatePassword")}
onClick={() => setForm({ ...form, password: randomPassword(policy) })}>
<Icon name="refresh-ccw" size={15} />
</button>
</div>
<PasswordRules policy={policy} value={form.password} />
</label>
<label style={{ minWidth: 160 }}>
<span>{t("users.role")}</span>
@@ -188,7 +221,8 @@ export default function Users() {
</label>
</div>
<p className="muted small">{t("users.passwordHint")}</p>
<button className="btn primary" type="submit" disabled={busy}>
<button className="btn primary" type="submit"
disabled={busy || !meetsPolicy(policy, form.password, t)}>
{busy ? t("common.loading") : t("common.create")}
</button>
</form>
+122
View File
@@ -0,0 +1,122 @@
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { api } from "../../api";
import { useToast } from "../../toast";
import Icon from "../../components/Icon";
import { DEFAULT_POLICY } from "../../passwordPolicy";
const SCHALTER = ["require_upper", "require_lower", "require_digit", "require_special"];
/**
* Passwortrichtlinie – gilt für die ganze Instanz, deshalb nur für Admins.
*
* Bewusst mit Speichern-Knopf statt „sofort übernehmen" wie bei den
* persönlichen Einstellungen: eine Verschärfung wirkt auf alle Benutzer, das
* soll ein bewusster Schritt sein.
*/
export default function PolicyCard() {
const { t } = useTranslation();
const toast = useToast();
const [policy, setPolicy] = useState(null);
const [entwurf, setEntwurf] = useState(DEFAULT_POLICY);
const [busy, setBusy] = useState(false);
const [fehler, setFehler] = useState(null);
useEffect(() => {
api.getPolicy()
.then((p) => { setPolicy(p); setEntwurf(p); })
.catch((err) => setFehler(err.message));
}, []);
const geaendert = policy && SCHALTER.concat("min_length", "mfa_required")
.some((k) => policy[k] !== entwurf[k]);
const verschaerft = policy && (
entwurf.min_length > policy.min_length ||
SCHALTER.some((k) => entwurf[k] && !policy[k])
);
const mfaNeu = policy && entwurf.mfa_required && !policy.mfa_required;
async function speichern() {
setBusy(true);
setFehler(null);
try {
const gespeichert = await api.setPolicy(entwurf);
setPolicy(gespeichert);
setEntwurf(gespeichert);
toast(t("settings.saved"));
} catch (err) {
setFehler(err.message);
} finally {
setBusy(false);
}
}
if (!policy) {
return (
<div className="card" style={{ maxWidth: 520, marginTop: "var(--sp-4)" }}>
<h2 style={{ marginTop: 0 }}>{t("policy.title")}</h2>
{fehler ? <div className="alert error"><Icon name="alert" size={16} /><span>{fehler}</span></div>
: <p className="muted small">{t("common.loading")}</p>}
</div>
);
}
return (
<div className="card" style={{ maxWidth: 520, marginTop: "var(--sp-4)" }}>
<h2 style={{ display: "flex", alignItems: "center", gap: "var(--sp-2)", marginTop: 0 }}>
<Icon name="lock" size={18} /> {t("policy.title")}
</h2>
<p className="muted small">{t("policy.hint")}</p>
{fehler && (
<div className="alert error" style={{ marginBottom: "var(--sp-3)" }}>
<Icon name="alert" size={16} /><span>{fehler}</span>
</div>
)}
<label>
<span>{t("policy.minLength")}</span>
<input type="number" min="8" max="128" value={entwurf.min_length}
onChange={(e) => {
const n = Math.max(8, Math.min(128, Number(e.target.value) || 8));
setEntwurf({ ...entwurf, min_length: n });
}} />
</label>
<div style={{ marginTop: "var(--sp-3)" }}>
{SCHALTER.map((k) => (
<label key={k} className="field-inline" style={{ marginBottom: 6 }}>
<input type="checkbox" checked={entwurf[k]}
onChange={(e) => setEntwurf({ ...entwurf, [k]: e.target.checked })} />
<span>{t(`policy.${k}`)}</span>
</label>
))}
</div>
<div style={{ marginTop: "var(--sp-4)", paddingTop: "var(--sp-3)", borderTop: "1px solid var(--border)" }}>
<label className="field-inline">
<input type="checkbox" checked={entwurf.mfa_required}
onChange={(e) => setEntwurf({ ...entwurf, mfa_required: e.target.checked })} />
<span>{t("policy.mfaRequired")}</span>
</label>
<p className="muted small" style={{ marginTop: 4 }}>{t("policy.mfaHint")}</p>
</div>
{verschaerft && (
<div className="alert warn" style={{ marginTop: "var(--sp-3)" }}>
<Icon name="alert" size={16} /><span>{t("policy.tightenWarning")}</span>
</div>
)}
{mfaNeu && (
<div className="alert warn" style={{ marginTop: "var(--sp-3)" }}>
<Icon name="shield" size={16} /><span>{t("policy.mfaWarning")}</span>
</div>
)}
<button className="btn primary" style={{ marginTop: "var(--sp-3)" }}
disabled={busy || !geaendert} onClick={speichern}>
{busy ? t("common.loading") : t("common.save")}
</button>
</div>
);
}
+169
View File
@@ -0,0 +1,169 @@
import { useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { api } from "../../api";
import { useAuth } from "../../auth";
import { useConfirm } from "../../confirm";
import { useToast } from "../../toast";
import Icon from "../../components/Icon";
/**
* Backup zurückladen – zweistufig wie der CSV-Import: erst prüfen lassen, was
* in der Datei steckt, dann bewusst bestätigen. Der Server schreibt beim Prüfen
* nichts.
*/
export default function RestoreCard() {
const { t } = useTranslation();
const toast = useToast();
const confirm = useConfirm();
const navigate = useNavigate();
const { logout } = useAuth();
const dateiFeld = useRef(null);
const [datei, setDatei] = useState(null);
const [vorschau, setVorschau] = useState(null);
const [modus, setModus] = useState("replace");
const [fehler, setFehler] = useState(null);
const [busy, setBusy] = useState(false);
function zuruecksetzen() {
setDatei(null);
setVorschau(null);
setFehler(null);
if (dateiFeld.current) dateiFeld.current.value = "";
}
async function pruefen(f) {
setDatei(f);
setVorschau(null);
setFehler(null);
if (!f) return;
setBusy(true);
try {
setVorschau(await api.restorePreview(f));
} catch (err) {
setFehler(err.message);
} finally {
setBusy(false);
}
}
async function einspielen() {
const systemweit = vorschau.scope === "system";
if (modus === "replace") {
const ok = await confirm({
title: t("restore.confirmTitle"),
message: systemweit ? t("restore.confirmSystem") : t("restore.confirmReplace"),
confirmLabel: t("restore.start"),
danger: true,
});
if (!ok) return;
}
setBusy(true);
setFehler(null);
try {
const res = await api.restoreBackup(datei, systemweit ? "replace" : modus);
if (res.logout_required) {
// Die eigene Sitzung wurde beim Ersetzen der Benutzertabelle mit
// gelöscht – sauber abmelden statt in 401er zu laufen.
toast(t("restore.doneSystem"));
await logout();
navigate("/login");
return;
}
toast(t("restore.done"));
zuruecksetzen();
// Konten, Kategorien und Einstellungen sind komplett andere – neu laden
// ist ehrlicher als jeden Zwischenspeicher einzeln zu erneuern.
window.location.reload();
} catch (err) {
setFehler(err.message);
setBusy(false);
}
}
return (
<div className="card" style={{ maxWidth: 520, marginTop: "var(--sp-4)" }}>
<h2 style={{ display: "flex", alignItems: "center", gap: "var(--sp-2)", marginTop: 0 }}>
<Icon name="upload" size={18} /> {t("restore.title")}
</h2>
<p className="muted small">{t("restore.hint")}</p>
{fehler && (
<div className="alert error" style={{ marginBottom: "var(--sp-3)" }}>
<Icon name="alert" size={16} /><span>{fehler}</span>
</div>
)}
<label>
<span>{t("restore.file")}</span>
<input ref={dateiFeld} type="file" accept="application/json,.json"
onChange={(e) => pruefen(e.target.files?.[0] || null)} />
</label>
{busy && !vorschau && <p className="muted small">{t("common.loading")}</p>}
{vorschau && (
<>
<div className="alert" style={{ marginTop: "var(--sp-3)" }}>
<Icon name="check" size={16} />
<div>
<div>
{vorschau.scope === "system"
? t("restore.scopeSystem", { n: vorschau.user_count })
: t("restore.scopeUser", { name: vorschau.username || "?" })}
</div>
<div className="muted small" style={{ marginTop: 2 }}>
{t("restore.exportedAt", { when: vorschau.exported_at || "?" })}
</div>
</div>
</div>
<table className="restore-summary">
<tbody>
{vorschau.tables.map((z) => (
<tr key={z.key}>
<td>{z.label}</td>
<td>{z.count}</td>
</tr>
))}
{vorschau.tables.length === 0 && (
<tr><td colSpan={2} className="muted">{t("restore.empty")}</td></tr>
)}
</tbody>
</table>
{vorschau.notes.map((n) => (
<div className="alert warn" key={n} style={{ marginTop: "var(--sp-3)" }}>
<Icon name="alert" size={16} /><span>{n}</span>
</div>
))}
{vorschau.scope === "user" && (
<label style={{ marginTop: "var(--sp-3)" }}>
<span>{t("restore.mode")}</span>
<select value={modus} onChange={(e) => setModus(e.target.value)}>
<option value="replace">{t("restore.modeReplace")}</option>
<option value="merge">{t("restore.modeMerge")}</option>
</select>
</label>
)}
<p className="muted small">
{vorschau.scope === "system" || modus === "replace"
? t("restore.modeReplaceHint")
: t("restore.modeMergeHint")}
</p>
<div className="btn-pair">
<button className="btn danger-solid" disabled={busy} onClick={einspielen}>
{busy ? t("common.loading") : t("restore.start")}
</button>
<button className="btn ghost" disabled={busy} onClick={zuruecksetzen}>
{t("common.cancel")}
</button>
</div>
</>
)}
</div>
);
}