Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+91
@@ -0,0 +1,91 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { MAX_ZOOM, MIN_ZOOM, centeredOffset, clampOffset, clampZoom, coverScale, cropRegion, offsetAfterZoom } from "./avatarCrop";
|
||||
|
||||
const landscape = { imageWidth: 800, imageHeight: 400, viewport: 200, zoom: 1 };
|
||||
const portrait = { imageWidth: 400, imageHeight: 800, viewport: 200, zoom: 1 };
|
||||
|
||||
describe("coverScale", () => {
|
||||
it("scales the shortest edge onto the viewport", () => {
|
||||
expect(coverScale(landscape)).toBe(0.5);
|
||||
expect(coverScale(portrait)).toBe(0.5);
|
||||
});
|
||||
|
||||
it("multiplies by the zoom factor", () => {
|
||||
expect(coverScale({ ...landscape, zoom: 2 })).toBe(1);
|
||||
});
|
||||
|
||||
it("returns 0 for an image that has no measurable size yet", () => {
|
||||
expect(coverScale({ ...landscape, imageWidth: 0, imageHeight: 0 })).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("clampZoom", () => {
|
||||
it("keeps the zoom inside the supported range", () => {
|
||||
expect(clampZoom(0.2)).toBe(MIN_ZOOM);
|
||||
expect(clampZoom(99)).toBe(MAX_ZOOM);
|
||||
expect(clampZoom(Number.NaN)).toBe(MIN_ZOOM);
|
||||
});
|
||||
});
|
||||
|
||||
describe("clampOffset", () => {
|
||||
it("never lets an empty gap slide into the viewport", () => {
|
||||
// 800x400 at scale 0.5 renders as 400x200, so x may travel from -200 to 0.
|
||||
expect(clampOffset(landscape, { x: 50, y: 0 })).toEqual({ x: 0, y: 0 });
|
||||
expect(clampOffset(landscape, { x: -900, y: 0 })).toEqual({ x: -200, y: 0 });
|
||||
});
|
||||
|
||||
it("pins the covered axis to 0 instead of inverting its range", () => {
|
||||
expect(clampOffset(landscape, { x: -10, y: -10 })).toEqual({ x: -10, y: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("centeredOffset", () => {
|
||||
it("centres the overhang of the long edge", () => {
|
||||
expect(centeredOffset(landscape)).toEqual({ x: -100, y: 0 });
|
||||
expect(centeredOffset(portrait)).toEqual({ x: 0, y: -100 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("offsetAfterZoom", () => {
|
||||
it("keeps the point in the middle of the viewport in the middle", () => {
|
||||
const start = centeredOffset(portrait);
|
||||
const zoomed = offsetAfterZoom(portrait, start, 2);
|
||||
|
||||
const before = cropRegion(portrait, start);
|
||||
const after = cropRegion({ ...portrait, zoom: 2 }, zoomed);
|
||||
|
||||
expect(after.sx + after.size / 2).toBeCloseTo(before.sx + before.size / 2, 5);
|
||||
expect(after.sy + after.size / 2).toBeCloseTo(before.sy + before.size / 2, 5);
|
||||
});
|
||||
|
||||
it("re-clamps so zooming out cannot expose a gap", () => {
|
||||
const panned = clampOffset({ ...portrait, zoom: 3 }, { x: -400, y: -1600 });
|
||||
const zoomedOut = offsetAfterZoom({ ...portrait, zoom: 3 }, panned, 1);
|
||||
|
||||
expect(zoomedOut).toEqual(clampOffset({ ...portrait, zoom: 1 }, zoomedOut));
|
||||
});
|
||||
});
|
||||
|
||||
describe("cropRegion", () => {
|
||||
it("maps the centred viewport onto the source pixels", () => {
|
||||
expect(cropRegion(landscape, centeredOffset(landscape))).toEqual({ sx: 200, sy: 0, size: 400 });
|
||||
});
|
||||
|
||||
it("shrinks the section as the user zooms in", () => {
|
||||
const geometry = { ...landscape, zoom: 2 };
|
||||
expect(cropRegion(geometry, centeredOffset(geometry)).size).toBe(200);
|
||||
});
|
||||
|
||||
it("follows a pan to the left edge", () => {
|
||||
expect(cropRegion(landscape, { x: 0, y: 0 })).toEqual({ sx: 0, sy: 0, size: 400 });
|
||||
});
|
||||
|
||||
it("stays inside the source image at every extreme", () => {
|
||||
const geometry = { ...landscape, zoom: 3 };
|
||||
const region = cropRegion(geometry, { x: -10_000, y: -10_000 });
|
||||
|
||||
expect(region.sx + region.size).toBeLessThanOrEqual(geometry.imageWidth);
|
||||
expect(region.sy + region.size).toBeLessThanOrEqual(geometry.imageHeight);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
// Geometry for the avatar crop dialog. The dialog shows a square viewport; the
|
||||
// picked image is scaled to cover it and can then be panned and zoomed until the
|
||||
// user sees exactly the section they want as their picture. The math lives here,
|
||||
// free of React and the DOM, so the clamping rules stay testable.
|
||||
|
||||
export type CropGeometry = {
|
||||
/** Natural size of the picked image, in source pixels. */
|
||||
imageWidth: number;
|
||||
imageHeight: number;
|
||||
/** Edge length of the square viewport, in CSS pixels. */
|
||||
viewport: number;
|
||||
/** 1 = the image exactly covers the viewport, higher means zoomed in. */
|
||||
zoom: number;
|
||||
};
|
||||
|
||||
export type CropOffset = {
|
||||
/** Position of the image's top-left corner relative to the viewport, in CSS pixels. */
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
|
||||
export type CropRegion = {
|
||||
/** Top-left corner of the visible section, in source pixels. */
|
||||
sx: number;
|
||||
sy: number;
|
||||
/** Edge length of the visible square section, in source pixels. */
|
||||
size: number;
|
||||
};
|
||||
|
||||
export const MIN_ZOOM = 1;
|
||||
export const MAX_ZOOM = 4;
|
||||
export const ZOOM_STEP = 0.05;
|
||||
|
||||
/** Edge length of the stored picture. Square, so every avatar renders the same. */
|
||||
export const OUTPUT_SIZE = 512;
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
if (Number.isNaN(value)) return min;
|
||||
return normalizeZero(Math.min(Math.max(value, min), max));
|
||||
}
|
||||
|
||||
/** Turn -0 into 0. Both render identically, but only one compares cleanly in tests. */
|
||||
function normalizeZero(value: number): number {
|
||||
return value + 0;
|
||||
}
|
||||
|
||||
export function clampZoom(zoom: number): number {
|
||||
return clamp(zoom, MIN_ZOOM, MAX_ZOOM);
|
||||
}
|
||||
|
||||
/** Scale that makes the image cover the square viewport at the given zoom. */
|
||||
export function coverScale(geometry: CropGeometry): number {
|
||||
const shortestEdge = Math.min(geometry.imageWidth, geometry.imageHeight);
|
||||
if (shortestEdge <= 0 || geometry.viewport <= 0) return 0;
|
||||
return (geometry.viewport / shortestEdge) * clampZoom(geometry.zoom);
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep the viewport covered: panning must never slide an empty gap into view.
|
||||
* `Math.min(…, 0)` absorbs the float wobble where a scaled edge lands a hair
|
||||
* below the viewport and would otherwise produce an inverted range.
|
||||
*/
|
||||
export function clampOffset(geometry: CropGeometry, offset: CropOffset): CropOffset {
|
||||
const scale = coverScale(geometry);
|
||||
if (scale <= 0) return { x: 0, y: 0 };
|
||||
|
||||
const minX = Math.min(geometry.viewport - geometry.imageWidth * scale, 0);
|
||||
const minY = Math.min(geometry.viewport - geometry.imageHeight * scale, 0);
|
||||
return { x: clamp(offset.x, minX, 0), y: clamp(offset.y, minY, 0) };
|
||||
}
|
||||
|
||||
/** Offset that centres the image in the viewport — the state a fresh pick starts in. */
|
||||
export function centeredOffset(geometry: CropGeometry): CropOffset {
|
||||
const scale = coverScale(geometry);
|
||||
if (scale <= 0) return { x: 0, y: 0 };
|
||||
|
||||
return clampOffset(geometry, {
|
||||
x: (geometry.viewport - geometry.imageWidth * scale) / 2,
|
||||
y: (geometry.viewport - geometry.imageHeight * scale) / 2,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Offset after a zoom change that keeps whatever sits in the middle of the
|
||||
* viewport in the middle. Zooming that drifts away from the chosen section would
|
||||
* force the user to re-aim after every slider nudge.
|
||||
*/
|
||||
export function offsetAfterZoom(geometry: CropGeometry, offset: CropOffset, nextZoom: number): CropOffset {
|
||||
const nextGeometry = { ...geometry, zoom: clampZoom(nextZoom) };
|
||||
const currentScale = coverScale(geometry);
|
||||
const nextScale = coverScale(nextGeometry);
|
||||
if (currentScale <= 0 || nextScale <= 0) return centeredOffset(nextGeometry);
|
||||
|
||||
const centre = geometry.viewport / 2;
|
||||
const sourceX = (centre - offset.x) / currentScale;
|
||||
const sourceY = (centre - offset.y) / currentScale;
|
||||
return clampOffset(nextGeometry, { x: centre - sourceX * nextScale, y: centre - sourceY * nextScale });
|
||||
}
|
||||
|
||||
/** The section of the source image the user currently sees, in source pixels. */
|
||||
export function cropRegion(geometry: CropGeometry, offset: CropOffset): CropRegion {
|
||||
const scale = coverScale(geometry);
|
||||
if (scale <= 0) return { sx: 0, sy: 0, size: 0 };
|
||||
|
||||
const clamped = clampOffset(geometry, offset);
|
||||
return { sx: normalizeZero(-clamped.x / scale), sy: normalizeZero(-clamped.y / scale), size: geometry.viewport / scale };
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import AvatarCropDialog from "./AvatarCropDialog";
|
||||
import { OUTPUT_SIZE } from "../avatarCrop";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ i18n: { language: "en" }, t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
const SOURCE = "data:image/png;base64,source";
|
||||
const CROPPED = "data:image/jpeg;base64,cropped";
|
||||
|
||||
let drawImage: ReturnType<typeof vi.fn>;
|
||||
let toDataURL: ReturnType<typeof vi.fn>;
|
||||
|
||||
/** jsdom has no canvas backend, so the 2d context is stubbed with the calls we assert on. */
|
||||
function stubCanvas({ context = true }: { context?: boolean } = {}) {
|
||||
drawImage = vi.fn();
|
||||
toDataURL = vi.fn(() => CROPPED);
|
||||
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation(
|
||||
() => (context ? ({ fillStyle: "", fillRect: vi.fn(), drawImage } as unknown as CanvasRenderingContext2D) : null)
|
||||
);
|
||||
vi.spyOn(HTMLCanvasElement.prototype, "toDataURL").mockImplementation(toDataURL);
|
||||
}
|
||||
|
||||
/** Report a landscape source picture: jsdom reports 0x0 for images it never fetches. */
|
||||
function loadImage({ width = 800, height = 400 }: { width?: number; height?: number } = {}) {
|
||||
const image = screen.getByAltText("settings.profile.avatar.crop.previewAlt") as HTMLImageElement;
|
||||
Object.defineProperty(image, "naturalWidth", { value: width, configurable: true });
|
||||
Object.defineProperty(image, "naturalHeight", { value: height, configurable: true });
|
||||
fireEvent.load(image);
|
||||
return image;
|
||||
}
|
||||
|
||||
function renderDialog(overrides: Partial<React.ComponentProps<typeof AvatarCropDialog>> = {}) {
|
||||
const onConfirm = vi.fn();
|
||||
const onCancel = vi.fn();
|
||||
render(<AvatarCropDialog source={SOURCE} onConfirm={onConfirm} onCancel={onCancel} {...overrides} />);
|
||||
return { onConfirm, onCancel };
|
||||
}
|
||||
|
||||
describe("AvatarCropDialog", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
stubCanvas();
|
||||
});
|
||||
|
||||
it("shows the picked file so the user decides the section before anything is stored", () => {
|
||||
renderDialog();
|
||||
|
||||
expect(screen.getByAltText("settings.profile.avatar.crop.previewAlt")).toHaveAttribute("src", SOURCE);
|
||||
expect(screen.getByRole("dialog")).toHaveAccessibleName("settings.profile.avatar.crop.title");
|
||||
});
|
||||
|
||||
it("keeps confirm disabled until the image has reported its size", () => {
|
||||
renderDialog();
|
||||
const confirm = screen.getByRole("button", { name: "settings.profile.avatar.crop.confirm" });
|
||||
|
||||
expect(confirm).toBeDisabled();
|
||||
loadImage();
|
||||
expect(confirm).toBeEnabled();
|
||||
});
|
||||
|
||||
it("hands back the centred square section of a wide picture", () => {
|
||||
const { onConfirm } = renderDialog();
|
||||
loadImage();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "settings.profile.avatar.crop.confirm" }));
|
||||
|
||||
// 800x400 centred: the 400px square starts 200px in from the left edge.
|
||||
expect(drawImage).toHaveBeenCalledWith(expect.anything(), 200, 0, 400, 400, 0, 0, OUTPUT_SIZE, OUTPUT_SIZE);
|
||||
expect(onConfirm).toHaveBeenCalledWith(CROPPED);
|
||||
});
|
||||
|
||||
it("crops a smaller section after zooming in", () => {
|
||||
renderDialog();
|
||||
loadImage();
|
||||
|
||||
fireEvent.change(screen.getByLabelText("settings.profile.avatar.crop.zoom"), { target: { value: "2" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "settings.profile.avatar.crop.confirm" }));
|
||||
|
||||
const [, sx, sy, size] = drawImage.mock.calls[0];
|
||||
expect(size).toBe(200);
|
||||
expect(sx).toBe(300);
|
||||
expect(sy).toBe(100);
|
||||
});
|
||||
|
||||
it("follows an arrow-key pan instead of always cropping the centre", () => {
|
||||
renderDialog();
|
||||
loadImage();
|
||||
|
||||
fireEvent.keyDown(screen.getByRole("group", { name: "settings.profile.avatar.crop.viewportLabel" }), { key: "ArrowRight" });
|
||||
fireEvent.click(screen.getByRole("button", { name: "settings.profile.avatar.crop.confirm" }));
|
||||
|
||||
// The 288px viewport covers 400 source pixels, so one 12px key press shifts the section by 12 / 0.72.
|
||||
expect(drawImage.mock.calls[0][1]).toBeCloseTo(200 + 12 / (288 / 400), 5);
|
||||
});
|
||||
|
||||
it("returns to the centred section on reset", () => {
|
||||
renderDialog();
|
||||
loadImage();
|
||||
|
||||
fireEvent.change(screen.getByLabelText("settings.profile.avatar.crop.zoom"), { target: { value: "3" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "settings.profile.avatar.crop.reset" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "settings.profile.avatar.crop.confirm" }));
|
||||
|
||||
expect(drawImage).toHaveBeenCalledWith(expect.anything(), 200, 0, 400, 400, 0, 0, OUTPUT_SIZE, OUTPUT_SIZE);
|
||||
});
|
||||
|
||||
it("cancels without handing back a picture", () => {
|
||||
const { onCancel, onConfirm } = renderDialog();
|
||||
loadImage();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "shared.cancel" }));
|
||||
|
||||
expect(onCancel).toHaveBeenCalledTimes(1);
|
||||
expect(onConfirm).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("closes on Escape like any other modal", () => {
|
||||
const { onCancel } = renderDialog();
|
||||
|
||||
fireEvent.keyDown(document, { key: "Escape" });
|
||||
|
||||
expect(onCancel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("explains an unreadable file instead of submitting nothing", () => {
|
||||
const { onConfirm } = renderDialog();
|
||||
|
||||
fireEvent.error(screen.getByAltText("settings.profile.avatar.crop.previewAlt"));
|
||||
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("settings.profile.avatar.crop.failed");
|
||||
expect(onConfirm).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports a missing canvas context in Klartext rather than crashing", () => {
|
||||
stubCanvas({ context: false });
|
||||
const { onConfirm } = renderDialog();
|
||||
loadImage();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "settings.profile.avatar.crop.confirm" }));
|
||||
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("settings.profile.avatar.crop.failed");
|
||||
expect(onConfirm).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FeatherRotateCcw, FeatherX, FeatherZoomIn, FeatherZoomOut } from "@subframe/core";
|
||||
import { Button } from "~/ui/components/Button";
|
||||
import { IconButton } from "~/ui/components/IconButton";
|
||||
import {
|
||||
MAX_ZOOM,
|
||||
MIN_ZOOM,
|
||||
OUTPUT_SIZE,
|
||||
ZOOM_STEP,
|
||||
type CropOffset,
|
||||
centeredOffset,
|
||||
clampOffset,
|
||||
clampZoom,
|
||||
cropRegion,
|
||||
offsetAfterZoom,
|
||||
} from "../avatarCrop";
|
||||
|
||||
// The picked file is never stored as-is: the user first decides which square
|
||||
// section becomes their picture. Without this step a wide photo would be
|
||||
// squeezed into the round avatar slot and cut wherever it happened to land.
|
||||
|
||||
/** Edge length of the crop viewport in CSS pixels; the round mask sits inside it. */
|
||||
const VIEWPORT = 288;
|
||||
|
||||
/** How far one arrow-key press pans, in CSS pixels. */
|
||||
const PAN_STEP = 12;
|
||||
|
||||
export type AvatarCropDialogProps = {
|
||||
/** Data URI of the freshly picked file. */
|
||||
source: string;
|
||||
submitting?: boolean;
|
||||
onCancel: () => void;
|
||||
onConfirm: (dataUri: string) => void;
|
||||
};
|
||||
|
||||
export default function AvatarCropDialog({ source, submitting = false, onCancel, onConfirm }: AvatarCropDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const imageRef = useRef<HTMLImageElement | null>(null);
|
||||
const dragRef = useRef<{ pointerId: number; startX: number; startY: number; startOffset: CropOffset } | null>(null);
|
||||
const [natural, setNatural] = useState<{ width: number; height: number } | null>(null);
|
||||
const [zoom, setZoom] = useState(MIN_ZOOM);
|
||||
const [offset, setOffset] = useState<CropOffset>({ x: 0, y: 0 });
|
||||
const [failed, setFailed] = useState(false);
|
||||
|
||||
const geometry = { imageWidth: natural?.width ?? 0, imageHeight: natural?.height ?? 0, viewport: VIEWPORT, zoom };
|
||||
const ready = Boolean(natural) && !failed;
|
||||
|
||||
const onImageLoad = useCallback((event: React.SyntheticEvent<HTMLImageElement>) => {
|
||||
const { naturalWidth, naturalHeight } = event.currentTarget;
|
||||
const loaded = { imageWidth: naturalWidth, imageHeight: naturalHeight, viewport: VIEWPORT, zoom: MIN_ZOOM };
|
||||
setNatural({ width: naturalWidth, height: naturalHeight });
|
||||
setZoom(MIN_ZOOM);
|
||||
setOffset(centeredOffset(loaded));
|
||||
}, []);
|
||||
|
||||
function changeZoom(next: number) {
|
||||
const nextZoom = clampZoom(next);
|
||||
setOffset((current) => offsetAfterZoom(geometry, current, nextZoom));
|
||||
setZoom(nextZoom);
|
||||
}
|
||||
|
||||
function pan(dx: number, dy: number) {
|
||||
setOffset((current) => clampOffset(geometry, { x: current.x + dx, y: current.y + dy }));
|
||||
}
|
||||
|
||||
function reset() {
|
||||
setZoom(MIN_ZOOM);
|
||||
setOffset(centeredOffset({ ...geometry, zoom: MIN_ZOOM }));
|
||||
}
|
||||
|
||||
function onPointerDown(event: React.PointerEvent<HTMLDivElement>) {
|
||||
if (!ready || event.button !== 0) return;
|
||||
dragRef.current = { pointerId: event.pointerId, startX: event.clientX, startY: event.clientY, startOffset: offset };
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
}
|
||||
|
||||
function onPointerMove(event: React.PointerEvent<HTMLDivElement>) {
|
||||
const drag = dragRef.current;
|
||||
if (!drag || drag.pointerId !== event.pointerId) return;
|
||||
event.preventDefault();
|
||||
setOffset(
|
||||
clampOffset(geometry, {
|
||||
x: drag.startOffset.x + (event.clientX - drag.startX),
|
||||
y: drag.startOffset.y + (event.clientY - drag.startY),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function endDrag(event: React.PointerEvent<HTMLDivElement>) {
|
||||
if (dragRef.current?.pointerId !== event.pointerId) return;
|
||||
dragRef.current = null;
|
||||
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
|
||||
event.currentTarget.releasePointerCapture(event.pointerId);
|
||||
}
|
||||
}
|
||||
|
||||
function onKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {
|
||||
const moves: Record<string, [number, number]> = {
|
||||
ArrowLeft: [PAN_STEP, 0],
|
||||
ArrowRight: [-PAN_STEP, 0],
|
||||
ArrowUp: [0, PAN_STEP],
|
||||
ArrowDown: [0, -PAN_STEP],
|
||||
};
|
||||
const move = moves[event.key];
|
||||
if (!move || !ready) return;
|
||||
event.preventDefault();
|
||||
pan(move[0], move[1]);
|
||||
}
|
||||
|
||||
// Escape closes the dialog like the cancel button — expected from any modal.
|
||||
useEffect(() => {
|
||||
function onEscape(event: KeyboardEvent) {
|
||||
if (event.key === "Escape") onCancel();
|
||||
}
|
||||
document.addEventListener("keydown", onEscape);
|
||||
return () => document.removeEventListener("keydown", onEscape);
|
||||
}, [onCancel]);
|
||||
|
||||
function confirm() {
|
||||
const image = imageRef.current;
|
||||
if (!image || !ready) return;
|
||||
|
||||
const region = cropRegion(geometry, offset);
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = OUTPUT_SIZE;
|
||||
canvas.height = OUTPUT_SIZE;
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) {
|
||||
setFailed(true);
|
||||
return;
|
||||
}
|
||||
|
||||
// JPEG has no alpha, so a transparent PNG would otherwise bake in black.
|
||||
context.fillStyle = "#ffffff";
|
||||
context.fillRect(0, 0, OUTPUT_SIZE, OUTPUT_SIZE);
|
||||
context.drawImage(image, region.sx, region.sy, region.size, region.size, 0, 0, OUTPUT_SIZE, OUTPUT_SIZE);
|
||||
onConfirm(canvas.toDataURL("image/jpeg", 0.92));
|
||||
}
|
||||
|
||||
const scale = ready ? (VIEWPORT / Math.min(geometry.imageWidth, geometry.imageHeight)) * zoom : 1;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="bg-surface-neutral-overlay fixed inset-0 z-50 flex flex-col items-center justify-center gap-2 px-4 py-4"
|
||||
data-ui-id="ui.settings.profile.avatarCrop.dialog"
|
||||
>
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={t("settings.profile.avatar.crop.title")}
|
||||
className="border-border-default bg-surface-neutral-secondary mobile:px-4 mobile:py-5 relative flex max-h-[90vh] w-full max-w-[480px] flex-col items-start gap-5 overflow-auto rounded-lg border border-solid px-6 py-6 shadow-lg"
|
||||
>
|
||||
<IconButton
|
||||
className="absolute top-3 right-3"
|
||||
variant="ghost"
|
||||
size="small"
|
||||
icon={<FeatherX />}
|
||||
aria-label={t("shared.close")}
|
||||
onClick={onCancel}
|
||||
data-ui-id="ui.settings.profile.avatarCrop.close"
|
||||
/>
|
||||
<div className="flex w-full flex-col items-start gap-1">
|
||||
<span className="text-heading- font-heading- text-text-neutral-primary">{t("settings.profile.avatar.crop.title")}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("settings.profile.avatar.crop.subtitle")}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{failed ? (
|
||||
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative" role="alert">
|
||||
{t("settings.profile.avatar.crop.failed")}
|
||||
</span>
|
||||
) : null}
|
||||
|
||||
<div className="flex w-full flex-col items-center gap-3">
|
||||
{/* The pan surface has no native equivalent: it is dragged with a pointer and panned with the
|
||||
arrow keys, so it has to take focus. No interactive role fits — "group" plus a label keeps
|
||||
it announced without claiming button or slider semantics it does not have. */}
|
||||
{/* eslint-disable jsx-a11y/no-noninteractive-element-interactions, jsx-a11y/no-noninteractive-tabindex */}
|
||||
<div
|
||||
role="group"
|
||||
tabIndex={0}
|
||||
aria-label={t("settings.profile.avatar.crop.viewportLabel")}
|
||||
style={{ width: VIEWPORT, height: VIEWPORT }}
|
||||
className="bg-surface-neutral-tertiary focus-visible:shadow-focus relative flex-none touch-none overflow-hidden rounded-lg select-none"
|
||||
onPointerDown={onPointerDown}
|
||||
onPointerMove={onPointerMove}
|
||||
onPointerUp={endDrag}
|
||||
onPointerCancel={endDrag}
|
||||
onKeyDown={onKeyDown}
|
||||
data-ui-id="ui.settings.profile.avatarCrop.viewport"
|
||||
>
|
||||
<img
|
||||
ref={imageRef}
|
||||
src={source}
|
||||
alt={t("settings.profile.avatar.crop.previewAlt")}
|
||||
onLoad={onImageLoad}
|
||||
onError={() => setFailed(true)}
|
||||
draggable={false}
|
||||
style={{
|
||||
width: ready ? geometry.imageWidth * scale : VIEWPORT,
|
||||
height: ready ? geometry.imageHeight * scale : VIEWPORT,
|
||||
transform: `translate(${offset.x}px, ${offset.y}px)`,
|
||||
}}
|
||||
className="absolute top-0 left-0 max-w-none"
|
||||
/>
|
||||
{/* Round mask: the dimmed surround shows what gets cut away. */}
|
||||
<div aria-hidden="true" className="rounded-round pointer-events-none absolute inset-0 shadow-[0_0_0_9999px_rgb(0_0_0/0.45)]" />
|
||||
</div>
|
||||
{/* eslint-enable jsx-a11y/no-noninteractive-element-interactions, jsx-a11y/no-noninteractive-tabindex */}
|
||||
|
||||
<div className="flex w-full items-center gap-3">
|
||||
<IconButton
|
||||
variant="ghost"
|
||||
size="small"
|
||||
icon={<FeatherZoomOut />}
|
||||
aria-label={t("settings.profile.avatar.crop.zoomOut")}
|
||||
disabled={!ready || zoom <= MIN_ZOOM}
|
||||
onClick={() => changeZoom(zoom - 10 * ZOOM_STEP)}
|
||||
data-ui-id="ui.settings.profile.avatarCrop.zoomOut"
|
||||
/>
|
||||
<input
|
||||
type="range"
|
||||
min={MIN_ZOOM}
|
||||
max={MAX_ZOOM}
|
||||
step={ZOOM_STEP}
|
||||
value={zoom}
|
||||
disabled={!ready}
|
||||
aria-label={t("settings.profile.avatar.crop.zoom")}
|
||||
onChange={(event) => changeZoom(Number(event.target.value))}
|
||||
className="accent-brand-brand-surface-solid-default h-1 shrink-0 grow basis-0 cursor-pointer"
|
||||
data-ui-id="ui.settings.profile.avatarCrop.zoom"
|
||||
/>
|
||||
<IconButton
|
||||
variant="ghost"
|
||||
size="small"
|
||||
icon={<FeatherZoomIn />}
|
||||
aria-label={t("settings.profile.avatar.crop.zoomIn")}
|
||||
disabled={!ready || zoom >= MAX_ZOOM}
|
||||
onClick={() => changeZoom(zoom + 10 * ZOOM_STEP)}
|
||||
data-ui-id="ui.settings.profile.avatarCrop.zoomIn"
|
||||
/>
|
||||
<IconButton
|
||||
variant="ghost"
|
||||
size="small"
|
||||
icon={<FeatherRotateCcw />}
|
||||
aria-label={t("settings.profile.avatar.crop.reset")}
|
||||
disabled={!ready}
|
||||
onClick={reset}
|
||||
data-ui-id="ui.settings.profile.avatarCrop.reset"
|
||||
/>
|
||||
</div>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary text-center">
|
||||
{t("settings.profile.avatar.crop.hint")}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="mobile:flex-col-reverse flex w-full items-center justify-end gap-2">
|
||||
<Button
|
||||
className="mobile:w-full"
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={onCancel}
|
||||
data-ui-id="ui.settings.profile.avatarCrop.cancel"
|
||||
>
|
||||
{t("shared.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
className="mobile:w-full"
|
||||
type="button"
|
||||
loading={submitting}
|
||||
disabled={!ready}
|
||||
onClick={confirm}
|
||||
data-ui-id="ui.settings.profile.avatarCrop.confirm"
|
||||
>
|
||||
{t("settings.profile.avatar.crop.confirm")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+1
-1
@@ -32,7 +32,7 @@ export default function ForgotPasswordScreen({
|
||||
icon={<FeatherMail />}
|
||||
tone="positive"
|
||||
title={t("account.forgot.sentTitle")}
|
||||
message={t("account.forgot.sentBody", { email })}
|
||||
message={t("account.forgot.sentBody")}
|
||||
hint={t("account.forgot.sentHint")}
|
||||
dataUiId="ui.auth.forgot.sent"
|
||||
>
|
||||
|
||||
+42
-52
@@ -20,11 +20,14 @@ export default function GroupsListView({
|
||||
items,
|
||||
canManage,
|
||||
onManageMembers,
|
||||
onCreate,
|
||||
}: {
|
||||
items: GroupWithDetails[];
|
||||
canManage: boolean;
|
||||
/** R-P2b bulk interim UI (AD-28): opens the group members dialog when provided. */
|
||||
onManageMembers?: (groupId: string) => void;
|
||||
/** Opens the create dialog from the empty state; omitted when the caller has none. */
|
||||
onCreate?: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { csrf = "" } = useRootData();
|
||||
@@ -34,24 +37,7 @@ export default function GroupsListView({
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-col items-start gap-4">
|
||||
<div className="flex w-full items-start justify-between gap-4 mobile:flex-col">
|
||||
<div className="flex flex-col items-start gap-1">
|
||||
<span className="text-title-page font-title-page text-text-neutral-primary mobile:text-subtitle mobile:font-subtitle">
|
||||
{t("models.group.plural")}
|
||||
</span>
|
||||
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-tertiary">
|
||||
{t("settings.members.groups.subtitle")}
|
||||
</span>
|
||||
</div>
|
||||
{canManage ? (
|
||||
<Link to="new" className="no-underline mobile:w-full" data-ui-id="ui.settings.groups.new">
|
||||
<Button variant="primary" icon={<FeatherPlus />} className="mobile:w-full">
|
||||
{t("settings.members.groups.createCta")}
|
||||
</Button>
|
||||
</Link>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* Page headline (title/subtitle + create CTA) lives in the route's shared PageHeader. */}
|
||||
<Table
|
||||
header={
|
||||
<Table.HeaderRow>
|
||||
@@ -88,10 +74,10 @@ export default function GroupsListView({
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{canManage ? (
|
||||
<Link to="new" className="no-underline">
|
||||
<Button variant="primary" icon={<FeatherPlus />}>{t("settings.members.groups.createCta")}</Button>
|
||||
</Link>
|
||||
{canManage && onCreate ? (
|
||||
<Button variant="primary" icon={<FeatherPlus />} onClick={onCreate}>
|
||||
{t("settings.members.groups.createCta")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</Table.Cell>
|
||||
@@ -108,37 +94,41 @@ export default function GroupsListView({
|
||||
<Table.Cell>
|
||||
<span className="whitespace-nowrap text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">{group.users.length}</span>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<div className="flex grow shrink-0 basis-0 items-center justify-end">
|
||||
{canManage ? (
|
||||
<SubframeCore.DropdownMenu.Root>
|
||||
<SubframeCore.DropdownMenu.Trigger asChild>
|
||||
<IconButton icon={<FeatherMoreHorizontal />} data-ui-id="ui.settings.groups.rowActions" />
|
||||
</SubframeCore.DropdownMenu.Trigger>
|
||||
<SubframeCore.DropdownMenu.Portal>
|
||||
<SubframeCore.DropdownMenu.Content side="bottom" align="end" sideOffset={4} asChild>
|
||||
<DropdownMenu>
|
||||
<Link to={group.id} className="no-underline">
|
||||
<DropdownMenu.DropdownItem icon={<FeatherEdit2 />}>{t("shared.edit")}</DropdownMenu.DropdownItem>
|
||||
</Link>
|
||||
{onManageMembers ? (
|
||||
<DropdownMenu.DropdownItem
|
||||
icon={<FeatherUsers />}
|
||||
onClick={() => onManageMembers(group.id)}
|
||||
data-ui-id="ui.settings.groups.manageMembers"
|
||||
>
|
||||
{t("settings.members.groups.bulk.manageAction")}
|
||||
</DropdownMenu.DropdownItem>
|
||||
) : null}
|
||||
<DropdownMenu.DropdownItem icon={<FeatherTrash />} onClick={() => setConfirmDelete({ id: group.id, name: group.name })}>
|
||||
{t("shared.delete")}
|
||||
<Table.Cell variant="align-right">
|
||||
{canManage ? (
|
||||
<SubframeCore.DropdownMenu.Root>
|
||||
<SubframeCore.DropdownMenu.Trigger asChild>
|
||||
<IconButton
|
||||
variant="ghost"
|
||||
size="small"
|
||||
icon={<FeatherMoreHorizontal />}
|
||||
aria-label={`${t("shared.actions")}: ${group.name}`}
|
||||
data-ui-id="ui.settings.groups.rowActions"
|
||||
/>
|
||||
</SubframeCore.DropdownMenu.Trigger>
|
||||
<SubframeCore.DropdownMenu.Portal>
|
||||
<SubframeCore.DropdownMenu.Content side="bottom" align="end" sideOffset={4} asChild>
|
||||
<DropdownMenu>
|
||||
<Link to={group.id} className="no-underline">
|
||||
<DropdownMenu.DropdownItem icon={<FeatherEdit2 />}>{t("shared.edit")}</DropdownMenu.DropdownItem>
|
||||
</Link>
|
||||
{onManageMembers ? (
|
||||
<DropdownMenu.DropdownItem
|
||||
icon={<FeatherUsers />}
|
||||
onClick={() => onManageMembers(group.id)}
|
||||
data-ui-id="ui.settings.groups.manageMembers"
|
||||
>
|
||||
{t("settings.members.groups.bulk.manageAction")}
|
||||
</DropdownMenu.DropdownItem>
|
||||
</DropdownMenu>
|
||||
</SubframeCore.DropdownMenu.Content>
|
||||
</SubframeCore.DropdownMenu.Portal>
|
||||
</SubframeCore.DropdownMenu.Root>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
<DropdownMenu.DropdownItem icon={<FeatherTrash />} onClick={() => setConfirmDelete({ id: group.id, name: group.name })}>
|
||||
{t("shared.delete")}
|
||||
</DropdownMenu.DropdownItem>
|
||||
</DropdownMenu>
|
||||
</SubframeCore.DropdownMenu.Content>
|
||||
</SubframeCore.DropdownMenu.Portal>
|
||||
</SubframeCore.DropdownMenu.Root>
|
||||
) : null}
|
||||
</Table.Cell>
|
||||
</Table.Row>
|
||||
))
|
||||
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import LoginForm from "./LoginForm";
|
||||
|
||||
const navigate = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("react-router", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("react-router")>();
|
||||
return {
|
||||
...actual,
|
||||
Form: ({ children, ...props }: React.FormHTMLAttributes<HTMLFormElement>) => <form {...props}>{children}</form>,
|
||||
Link: ({ children, to, ...props }: React.AnchorHTMLAttributes<HTMLAnchorElement> & { to: string }) => (
|
||||
<a href={to} {...props}>
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
useNavigate: () => navigate,
|
||||
useNavigation: () => ({ state: "idle" }),
|
||||
useSearchParams: () => [new URLSearchParams()],
|
||||
};
|
||||
});
|
||||
|
||||
const translations: Record<string, string> = {
|
||||
"account.login.button": "Log in",
|
||||
"account.login.forgot": "Forgot your password?",
|
||||
"account.login.headline": "Welcome back.",
|
||||
"account.login.passwordPlaceholder": "Enter your password",
|
||||
"account.shared.email": "Email",
|
||||
"account.shared.emailPlaceholder": "name@company.com",
|
||||
"account.shared.password": "Password",
|
||||
"api.errors.invalidPassword": "Email or password is incorrect.",
|
||||
"shared.invalid": "Invalid",
|
||||
};
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string) => translations[key] ?? key,
|
||||
i18n: { exists: (key: string) => key in translations },
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useRootData", () => ({
|
||||
useRootData: () => ({
|
||||
csrf: "csrf-token",
|
||||
appConfiguration: {
|
||||
auth: { authMethods: { emailPassword: { enabled: true } } },
|
||||
subscription: { allowSignUpBeforeSubscribe: false },
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/buttons/LoadingButton", () => ({
|
||||
default: ({ children, actionName: _actionName, dataUiId, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement> & { actionName?: string; dataUiId?: string }) => (
|
||||
<button {...props} data-ui-id={dataUiId}>
|
||||
{children}
|
||||
</button>
|
||||
),
|
||||
}));
|
||||
|
||||
describe("LoginForm password handling", () => {
|
||||
it("clears its controlled password state after every credential response", () => {
|
||||
const { rerender } = render(<LoginForm actionData={undefined} />);
|
||||
const passwordInput = screen.getByPlaceholderText("Enter your password");
|
||||
|
||||
fireEvent.change(passwordInput, { target: { value: "first-wrong-secret" } });
|
||||
expect(passwordInput).toHaveValue("first-wrong-secret");
|
||||
|
||||
rerender(
|
||||
<LoginForm
|
||||
actionData={{
|
||||
error: "Email or password is incorrect.",
|
||||
fields: { email: "user@example.com" },
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(passwordInput).toHaveValue("");
|
||||
expect(passwordInput).toHaveFocus();
|
||||
|
||||
fireEvent.change(passwordInput, { target: { value: "second-wrong-secret" } });
|
||||
rerender(
|
||||
<LoginForm
|
||||
actionData={{
|
||||
error: "Email or password is incorrect.",
|
||||
fields: { email: "user@example.com" },
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(passwordInput).toHaveValue("");
|
||||
expect(passwordInput).toHaveFocus();
|
||||
});
|
||||
});
|
||||
+22
-4
@@ -1,5 +1,5 @@
|
||||
import { Form, Link, useNavigate, useNavigation, useSearchParams } from "react-router";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import LoadingButton from "~/components/ui/buttons/LoadingButton";
|
||||
import ExclamationTriangleIcon from "~/components/ui/icons/ExclamationTriangleIcon";
|
||||
@@ -14,7 +14,6 @@ export type LoginActionData = {
|
||||
};
|
||||
fields?: {
|
||||
email: string;
|
||||
password: string;
|
||||
};
|
||||
/**
|
||||
* D1: set when the password is valid but the user has 2FA enabled. The session cookie only
|
||||
@@ -44,6 +43,14 @@ export default function LoginForm({ actionData, redirectTo }: { actionData: Logi
|
||||
const mfaVerifyPath = actionData?.mfaVerifyPath ?? "/login-mfa";
|
||||
|
||||
const emailInput = useRef<RefInputText>(null);
|
||||
const passwordInput = useRef<RefInputText>(null);
|
||||
const [password, setPassword] = useState("");
|
||||
const passwordFieldError = Boolean(
|
||||
actionData?.fieldErrors?.password || actionData?.error === t("api.errors.invalidPassword")
|
||||
);
|
||||
const shouldClearPassword = Boolean(
|
||||
actionData && (actionData.fieldErrors?.password || actionData.error || actionData.requiresCaptcha)
|
||||
);
|
||||
useEffect(() => {
|
||||
if (appConfiguration.auth.authMethods.emailPassword.enabled) {
|
||||
setTimeout(() => {
|
||||
@@ -59,6 +66,15 @@ export default function LoginForm({ actionData, redirectTo }: { actionData: Logi
|
||||
}
|
||||
}, [actionData?.requiresMfa, mfaVerifyPath, navigate]);
|
||||
|
||||
useEffect(() => {
|
||||
if (shouldClearPassword) {
|
||||
setPassword("");
|
||||
}
|
||||
if (passwordFieldError) {
|
||||
passwordInput.current?.input.current?.focus();
|
||||
}
|
||||
}, [actionData, passwordFieldError, shouldClearPassword]);
|
||||
|
||||
if (actionData?.requiresMfa) {
|
||||
return (
|
||||
<div className="space-y-4 text-center" data-ui-id="ui.auth.login.mfaRedirect">
|
||||
@@ -120,6 +136,7 @@ export default function LoginForm({ actionData, redirectTo }: { actionData: Logi
|
||||
{t("account.shared.password")}
|
||||
</label> */}
|
||||
<InputText
|
||||
ref={passwordInput}
|
||||
id="password"
|
||||
title={t("account.shared.password")}
|
||||
name="password"
|
||||
@@ -129,9 +146,10 @@ export default function LoginForm({ actionData, redirectTo }: { actionData: Logi
|
||||
ariaDescribedBy={passwordErrorId}
|
||||
ariaInvalid={passwordErrorId ? true : undefined}
|
||||
// className="focus:border-theme-500 focus:ring-ring relative mt-1 block w-full appearance-none rounded-md border border-border px-3 py-2 text-sm text-foreground placeholder-gray-500 focus:z-10 focus:outline-hidden sm:text-sm dark:border-gray-700 dark:bg-gray-900 dark:text-slate-200"
|
||||
placeholder="************"
|
||||
placeholder={t("account.login.passwordPlaceholder")}
|
||||
value={password}
|
||||
setValue={setPassword}
|
||||
disabled={navigation.state !== "idle"}
|
||||
defaultValue={actionData?.fields?.password}
|
||||
/>
|
||||
{actionData?.fieldErrors?.password ? (
|
||||
<p className="text-destructive-foreground py-2 text-xs" role="alert" id="password-error">
|
||||
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import LoginScreen from "./LoginScreen";
|
||||
import type { LoginActionData } from "./LoginForm";
|
||||
|
||||
const navigate = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("react-router", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("react-router")>();
|
||||
return {
|
||||
...actual,
|
||||
Form: ({ children, ...props }: React.FormHTMLAttributes<HTMLFormElement>) => <form {...props}>{children}</form>,
|
||||
Link: ({ children, to, ...props }: React.AnchorHTMLAttributes<HTMLAnchorElement> & { to: string }) => (
|
||||
<a href={to} {...props}>
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
useNavigate: () => navigate,
|
||||
useNavigation: () => ({ state: "idle" }),
|
||||
useSearchParams: () => [new URLSearchParams()],
|
||||
};
|
||||
});
|
||||
|
||||
const translations: Record<string, string> = {
|
||||
"account.login.button": "Log in",
|
||||
"account.login.divider": "or",
|
||||
"account.login.forgot": "Forgot your password?",
|
||||
"account.login.headline": "Welcome back.",
|
||||
"account.login.invalidCredentialsDescription": "Please check your details and try again.",
|
||||
"account.login.invalidCredentialsTitle": "Email or password is incorrect.",
|
||||
"account.login.magicLink": "Sign in with magic link",
|
||||
"account.login.noAccount": "No account yet?",
|
||||
"account.login.passwordPlaceholder": "Enter your password",
|
||||
"account.login.register": "Sign up",
|
||||
"account.login.title": "Log in",
|
||||
"account.shared.email": "Email",
|
||||
"account.shared.emailPlaceholder": "name@company.com",
|
||||
"account.shared.password": "Password",
|
||||
"api.errors.invalidPassword": "Email or password is incorrect.",
|
||||
};
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => translations[key] ?? key }),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useRootData", () => ({
|
||||
useRootData: () => ({
|
||||
csrf: "csrf-token",
|
||||
appConfiguration: {
|
||||
auth: {
|
||||
captcha: {
|
||||
enabled: false,
|
||||
provider: "mcaptcha",
|
||||
instanceUrl: undefined,
|
||||
loginSiteKey: undefined,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/captcha/Captcha", () => ({ default: () => null }));
|
||||
|
||||
describe("LoginScreen", () => {
|
||||
it("shows a clear password placeholder instead of mask characters", () => {
|
||||
render(<LoginScreen actionData={undefined} />);
|
||||
|
||||
const passwordInput = screen.getByLabelText("Password");
|
||||
expect(passwordInput).toHaveValue("");
|
||||
expect(passwordInput).toHaveAttribute("placeholder", "Enter your password");
|
||||
expect(passwordInput.getAttribute("placeholder")).not.toMatch(/^[*•]+$/u);
|
||||
});
|
||||
|
||||
it("focuses and describes the password field after a server validation error without restoring the submitted secret", () => {
|
||||
const { rerender } = render(<LoginScreen actionData={undefined} />);
|
||||
const passwordInput = screen.getByLabelText("Password");
|
||||
fireEvent.change(passwordInput, { target: { value: "user-submitted-secret" } });
|
||||
expect(passwordInput).toHaveValue("user-submitted-secret");
|
||||
|
||||
const responseWithLegacySecret = {
|
||||
fieldErrors: { email: undefined, password: "Invalid password" },
|
||||
fields: { email: "user@example.com", password: "must-not-be-restored" },
|
||||
} as unknown as LoginActionData;
|
||||
rerender(<LoginScreen actionData={responseWithLegacySecret} />);
|
||||
|
||||
expect(passwordInput).toHaveFocus();
|
||||
expect(passwordInput).toHaveValue("");
|
||||
expect(passwordInput).toHaveAttribute("aria-invalid", "true");
|
||||
expect(passwordInput).toHaveAttribute("aria-describedby", "login-password-error");
|
||||
expect(passwordInput).toHaveAccessibleDescription("Invalid password");
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("Invalid password");
|
||||
});
|
||||
|
||||
it("describes both fields after server validation errors", () => {
|
||||
render(
|
||||
<LoginScreen
|
||||
actionData={{
|
||||
fieldErrors: { email: "Invalid email", password: "Invalid password" },
|
||||
fields: { email: "not-an-email" },
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
const emailInput = screen.getByLabelText("Email");
|
||||
const passwordInput = screen.getByLabelText("Password");
|
||||
expect(emailInput).toHaveAttribute("aria-invalid", "true");
|
||||
expect(emailInput).toHaveAttribute("aria-describedby", "login-email-error");
|
||||
expect(emailInput).toHaveAccessibleDescription("Invalid email");
|
||||
expect(passwordInput).toHaveAttribute("aria-invalid", "true");
|
||||
expect(passwordInput).toHaveAccessibleDescription("Invalid password");
|
||||
expect(screen.getAllByRole("alert")).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("focuses and describes the password field after generic invalid credentials", () => {
|
||||
const { rerender } = render(<LoginScreen actionData={undefined} />);
|
||||
const passwordInput = screen.getByLabelText("Password");
|
||||
fireEvent.change(passwordInput, { target: { value: "first-wrong-secret" } });
|
||||
|
||||
rerender(
|
||||
<LoginScreen
|
||||
actionData={{
|
||||
error: "Email or password is incorrect.",
|
||||
fields: { email: "user@example.com" },
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(passwordInput).toHaveFocus();
|
||||
expect(passwordInput).toHaveValue("");
|
||||
expect(passwordInput).toHaveAttribute("aria-invalid", "true");
|
||||
expect(passwordInput).toHaveAccessibleDescription("Email or password is incorrect.");
|
||||
|
||||
fireEvent.change(passwordInput, { target: { value: "second-wrong-secret" } });
|
||||
rerender(
|
||||
<LoginScreen
|
||||
actionData={{
|
||||
error: "Email or password is incorrect.",
|
||||
fields: { email: "user@example.com" },
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(passwordInput).toHaveFocus();
|
||||
expect(passwordInput).toHaveValue("");
|
||||
});
|
||||
});
|
||||
+70
-30
@@ -34,11 +34,19 @@ export default function LoginScreen({
|
||||
const emailError = actionData?.fieldErrors?.email;
|
||||
const passwordError = actionData?.fieldErrors?.password;
|
||||
const loginEmailRef = useRef<HTMLInputElement | null>(null);
|
||||
const loginPasswordRef = useRef<HTMLInputElement | null>(null);
|
||||
const [loginPassword, setLoginPassword] = useState("");
|
||||
const [magicRequestOpen, setMagicRequestOpen] = useState(Boolean(actionData?.magicLinkRequest));
|
||||
const [magicEmail, setMagicEmail] = useState(actionData?.magicLinkEmail ?? actionData?.fields?.email ?? "");
|
||||
const showMagicRequest = !actionData?.magicLinkSent && (magicRequestOpen || Boolean(actionData?.magicLinkRequest));
|
||||
const invalidCredentials = actionData?.error === t("api.errors.invalidPassword");
|
||||
const credentialFieldError = invalidCredentials ? t("account.login.invalidCredentialsTitle") : undefined;
|
||||
const passwordFieldError = credentialFieldError ?? passwordError;
|
||||
const emailErrorId = emailError ? "login-email-error" : undefined;
|
||||
const passwordErrorId = passwordFieldError ? "login-password-error" : undefined;
|
||||
const shouldClearPassword = Boolean(
|
||||
actionData && !actionData.magicLinkRequest && !actionData.magicLinkSent && (passwordError || actionData.error || actionData.requiresCaptcha)
|
||||
);
|
||||
const formError = actionData?.error && !actionData.requiresCaptcha ? actionData.error : undefined;
|
||||
const captchaSitekey = actionData?.sitekey ?? appConfiguration.auth.captcha.loginSiteKey;
|
||||
const compactActionButtons = Boolean(invalidCredentials || actionData?.requiresCaptcha);
|
||||
@@ -50,6 +58,15 @@ export default function LoginScreen({
|
||||
}
|
||||
}, [actionData?.requiresMfa, mfaVerifyPath, navigate]);
|
||||
|
||||
useEffect(() => {
|
||||
if (shouldClearPassword) {
|
||||
setLoginPassword("");
|
||||
}
|
||||
if (passwordFieldError) {
|
||||
loginPasswordRef.current?.focus();
|
||||
}
|
||||
}, [actionData, passwordFieldError, shouldClearPassword]);
|
||||
|
||||
if (actionData?.requiresMfa) {
|
||||
return (
|
||||
<AuthShell title={t("account.loginMfa.title")} dataUiId="ui.auth.login.page">
|
||||
@@ -193,14 +210,14 @@ export default function LoginScreen({
|
||||
<span
|
||||
className={
|
||||
compactActionButtons
|
||||
? "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary"
|
||||
: "text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary"
|
||||
? "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary"
|
||||
: "text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary"
|
||||
}
|
||||
>
|
||||
{t("account.login.noAccount")}
|
||||
</span>
|
||||
<Link to="/signup" className="no-underline" data-ui-id="ui.auth.login.register">
|
||||
<LinkButton size="small" hideIcon>
|
||||
<LinkButton size="small" variant="subtle" hideIcon>
|
||||
{t("account.login.register")}
|
||||
</LinkButton>
|
||||
</Link>
|
||||
@@ -262,28 +279,40 @@ export default function LoginScreen({
|
||||
</Card>
|
||||
</>
|
||||
) : null}
|
||||
<TextInput
|
||||
className="h-auto w-full flex-none"
|
||||
fillContainer
|
||||
showLabel
|
||||
label={t("account.shared.email")}
|
||||
helpText={credentialFieldError ? "" : emailError ?? ""}
|
||||
message={credentialFieldError ?? ""}
|
||||
error={Boolean(emailError || credentialFieldError)}
|
||||
type="email"
|
||||
>
|
||||
<TextInput.Input
|
||||
ref={loginEmailRef}
|
||||
name="email"
|
||||
<div className="flex w-full flex-col items-start gap-2">
|
||||
<TextInput
|
||||
className="h-auto w-full flex-none"
|
||||
fillContainer
|
||||
showLabel
|
||||
label={t("account.shared.email")}
|
||||
message={credentialFieldError ?? ""}
|
||||
error={Boolean(emailError || credentialFieldError)}
|
||||
type="email"
|
||||
required
|
||||
autoComplete="email"
|
||||
placeholder={t("account.shared.emailPlaceholder")}
|
||||
defaultValue={actionData?.fields?.email}
|
||||
disabled={isSubmitting}
|
||||
data-ui-id="ui.auth.login.email"
|
||||
/>
|
||||
</TextInput>
|
||||
>
|
||||
<TextInput.Input
|
||||
ref={loginEmailRef}
|
||||
name="email"
|
||||
type="email"
|
||||
required
|
||||
autoComplete="email"
|
||||
placeholder={t("account.shared.emailPlaceholder")}
|
||||
defaultValue={actionData?.fields?.email}
|
||||
disabled={isSubmitting}
|
||||
aria-invalid={emailError ? true : undefined}
|
||||
aria-describedby={emailErrorId}
|
||||
data-ui-id="ui.auth.login.email"
|
||||
/>
|
||||
</TextInput>
|
||||
{emailError ? (
|
||||
<span
|
||||
id={emailErrorId}
|
||||
className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative"
|
||||
role="alert"
|
||||
>
|
||||
{emailError}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="flex w-full flex-col items-start gap-2">
|
||||
<TextInput
|
||||
@@ -291,26 +320,37 @@ export default function LoginScreen({
|
||||
fillContainer
|
||||
showLabel
|
||||
label={t("account.shared.password")}
|
||||
helpText={credentialFieldError ? "" : passwordError ?? ""}
|
||||
message={credentialFieldError ?? ""}
|
||||
error={Boolean(passwordError || credentialFieldError)}
|
||||
error={Boolean(passwordFieldError)}
|
||||
type="password"
|
||||
>
|
||||
<TextInput.Input
|
||||
ref={loginPasswordRef}
|
||||
name="password"
|
||||
type="password"
|
||||
required
|
||||
autoComplete="current-password"
|
||||
placeholder={t("account.shared.passwordPlaceholder")}
|
||||
defaultValue={actionData?.fields?.password}
|
||||
placeholder={t("account.login.passwordPlaceholder")}
|
||||
value={loginPassword}
|
||||
onChange={(event) => setLoginPassword(event.target.value)}
|
||||
disabled={isSubmitting}
|
||||
aria-invalid={passwordFieldError ? true : undefined}
|
||||
aria-describedby={passwordErrorId}
|
||||
data-ui-id="ui.auth.login.password"
|
||||
/>
|
||||
</TextInput>
|
||||
{passwordFieldError ? (
|
||||
<span
|
||||
id={passwordErrorId}
|
||||
className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative"
|
||||
role="alert"
|
||||
>
|
||||
{passwordFieldError}
|
||||
</span>
|
||||
) : null}
|
||||
|
||||
<div className="flex w-full items-start justify-end">
|
||||
<Link to="/forgot-password" className="no-underline" data-ui-id="ui.auth.login.forgot">
|
||||
<LinkButton size="small" hideIcon>
|
||||
<LinkButton size="small" variant="subtle" hideIcon>
|
||||
{t("account.login.forgot")}
|
||||
</LinkButton>
|
||||
</Link>
|
||||
|
||||
+5
-1
@@ -94,7 +94,11 @@ export default function MembersListView({
|
||||
{canEdit ? (
|
||||
<SubframeCore.DropdownMenu.Root>
|
||||
<SubframeCore.DropdownMenu.Trigger asChild>
|
||||
<IconButton icon={<FeatherMoreHorizontal />} data-ui-id="ui.settings.members.rowActions" />
|
||||
<IconButton
|
||||
icon={<FeatherMoreHorizontal />}
|
||||
aria-label={`${t("shared.actions")}: ${name}`}
|
||||
data-ui-id="ui.settings.members.rowActions"
|
||||
/>
|
||||
</SubframeCore.DropdownMenu.Trigger>
|
||||
<SubframeCore.DropdownMenu.Portal>
|
||||
<SubframeCore.DropdownMenu.Content side="bottom" align="end" sideOffset={4} asChild>
|
||||
|
||||
+244
-127
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Form, useActionData, useNavigation, useSubmit } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { formatDate } from "~/locale/format";
|
||||
import { QRCodeSVG } from "qrcode.react";
|
||||
import {
|
||||
FeatherArrowLeft,
|
||||
@@ -22,6 +23,7 @@ import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
|
||||
import { Button } from "~/ui/components/Button";
|
||||
import { Card } from "~/ui/components/Card";
|
||||
import { CopyToClipboardButton } from "~/ui/components/CopyToClipboardButton";
|
||||
import { Dialog } from "~/ui/components/Dialog";
|
||||
import { IconButton } from "~/ui/components/IconButton";
|
||||
import { IconWithBackground } from "~/ui/components/IconWithBackground";
|
||||
import { InputOtp } from "~/ui/components/InputOtp";
|
||||
@@ -30,6 +32,7 @@ import { Select } from "~/ui/components/Select";
|
||||
import { TextInput } from "~/ui/components/TextInput";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import AvatarCropDialog from "./AvatarCropDialog";
|
||||
|
||||
// D-P2 — Settings > Profil nach Davids Subframe-"My Profile"-Design: Profil-Card (Avatar + Name inline-edit +
|
||||
// E-Mail read-only) + Sicherheits-Card (Passwort ändern -> Modal, 2FA -> Verwalten/Setup/Disable-Modal). Praesentational,
|
||||
@@ -72,14 +75,14 @@ function userDisplayName(user: ProfileUser): string {
|
||||
// hier 1:1 als Markup nachgebaut, OHNE die Settings-Shell/Navigation umzubauen.
|
||||
function NeutralCard({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex h-full w-full flex-col items-start gap-3 rounded-lg bg-surface-neutral-secondary px-4 py-4">
|
||||
<div className="flex w-full grow shrink-0 basis-0 flex-col items-start gap-3">{children}</div>
|
||||
<div className="bg-surface-neutral-secondary flex h-full w-full flex-col items-start gap-3 rounded-lg px-4 py-4">
|
||||
<div className="flex w-full shrink-0 grow basis-0 flex-col items-start gap-3">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CardDivider() {
|
||||
return <div className="flex h-px w-full flex-col items-center gap-2 bg-surface-neutral-tertiary" />;
|
||||
return <div className="bg-surface-neutral-tertiary flex h-px w-full flex-col items-center gap-2" />;
|
||||
}
|
||||
|
||||
function SettingRow({ label, helpText, children }: { label: React.ReactNode; helpText?: React.ReactNode; children: React.ReactNode }) {
|
||||
@@ -88,10 +91,10 @@ function SettingRow({ label, helpText, children }: { label: React.ReactNode; hel
|
||||
<div className="flex flex-col items-start gap-1">
|
||||
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{label}</span>
|
||||
{helpText ? (
|
||||
<span className="w-full text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">{helpText}</span>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary w-full">{helpText}</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex grow shrink-0 basis-0 items-center justify-end">{children}</div>
|
||||
<div className="flex shrink-0 grow basis-0 items-center justify-end">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -147,6 +150,8 @@ export default function MyProfileScreen({
|
||||
const fileInput = useRef<HTMLInputElement | null>(null);
|
||||
const avatarForm = useRef<HTMLFormElement | null>(null);
|
||||
const [avatarData, setAvatarData] = useState<string>("");
|
||||
// Data URI of the picked file while the crop dialog is open; null when closed.
|
||||
const [cropSource, setCropSource] = useState<string | null>(null);
|
||||
|
||||
// Schritt-Übergänge des 2FA-Flows aus der Action-Antwort ableiten.
|
||||
useEffect(() => {
|
||||
@@ -164,17 +169,24 @@ export default function MyProfileScreen({
|
||||
if (!mfaStatus?.enabled && (twoFa === "disable" || twoFa === "manage")) setTwoFa(null);
|
||||
}, [mfaStatus?.enabled, twoFa]);
|
||||
|
||||
// A picked file goes into the crop dialog first; only the section the user
|
||||
// confirmed there is submitted. Clearing the input lets the same file be
|
||||
// picked again after a cancel, which otherwise fires no change event.
|
||||
function onPickAvatar(event: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = event.target.files?.[0];
|
||||
event.target.value = "";
|
||||
if (!file) return;
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
setAvatarData(String(reader.result ?? ""));
|
||||
requestAnimationFrame(() => avatarForm.current && submit(avatarForm.current));
|
||||
};
|
||||
reader.onload = () => setCropSource(String(reader.result ?? ""));
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
|
||||
function onCropConfirmed(dataUri: string) {
|
||||
setCropSource(null);
|
||||
setAvatarData(dataUri);
|
||||
requestAnimationFrame(() => avatarForm.current && submit(avatarForm.current));
|
||||
}
|
||||
|
||||
const mfaEnabled = Boolean(mfaStatus?.enabled);
|
||||
const roleName = role === null || role === undefined ? "" : TenantUserType[role];
|
||||
const roleLabel = roleName ? t(`settings.profile.types.${roleName}`) : "";
|
||||
@@ -182,30 +194,20 @@ export default function MyProfileScreen({
|
||||
return (
|
||||
<div className="flex w-full flex-col items-start gap-4" data-ui-id="ui.settings.profile.page">
|
||||
<div className="flex w-full flex-col items-start gap-4">
|
||||
{/* Header */}
|
||||
<div className="flex w-full flex-col items-start gap-2">
|
||||
<span className="text-title-page font-title-page text-text-neutral-primary mobile:text-subtitle mobile:font-subtitle">
|
||||
{t("settings.profile.accountSettings.title")}
|
||||
</span>
|
||||
<span className="w-full text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-tertiary">
|
||||
{t("settings.profile.accountSettings.description")}
|
||||
</span>
|
||||
</div>
|
||||
{/* Page headline (title/subtitle) lives in the route's shared PageHeader. */}
|
||||
|
||||
{/* Reihe 1 — Profil + Accountsicherheit */}
|
||||
<div className="flex w-full items-start gap-4 mobile:flex-col">
|
||||
<div className="mobile:flex-col flex w-full items-start gap-4">
|
||||
<NeutralCard>
|
||||
<div className="flex w-full items-center gap-6 mobile:flex-col mobile:items-start">
|
||||
<div className="flex grow shrink-0 basis-0 items-center gap-4">
|
||||
<Avatar size="large" image={user.avatar ?? undefined}>
|
||||
<div className="mobile:flex-col mobile:items-start flex w-full items-center gap-6">
|
||||
<div className="flex shrink-0 grow basis-0 items-center gap-4">
|
||||
<Avatar size="extra-large" image={user.avatar ?? undefined}>
|
||||
{initials(user)}
|
||||
</Avatar>
|
||||
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-3">
|
||||
<div className="flex shrink-0 grow basis-0 flex-col items-start gap-3">
|
||||
<div className="flex flex-col items-start gap-0.5">
|
||||
<span className="text-heading- font-heading- text-text-neutral-primary">{userDisplayName(user)}</span>
|
||||
{roleLabel ? (
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{roleLabel}</span>
|
||||
) : null}
|
||||
{roleLabel ? <span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{roleLabel}</span> : null}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{/* Bild ändern (Avatar-Upload, autosubmit per onPick) */}
|
||||
@@ -215,7 +217,14 @@ export default function MyProfileScreen({
|
||||
<input type="hidden" name="firstName" value={user.firstName ?? ""} readOnly />
|
||||
<input type="hidden" name="lastName" value={user.lastName ?? ""} readOnly />
|
||||
<input type="hidden" name="avatar" value={avatarData} readOnly />
|
||||
<input ref={fileInput} type="file" accept="image/png,image/jpeg" className="hidden" onChange={onPickAvatar} data-ui-id="ui.settings.profile.avatarInput" />
|
||||
<input
|
||||
ref={fileInput}
|
||||
type="file"
|
||||
accept="image/png,image/jpeg"
|
||||
className="hidden"
|
||||
onChange={onPickAvatar}
|
||||
data-ui-id="ui.settings.profile.avatarInput"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
@@ -249,19 +258,18 @@ export default function MyProfileScreen({
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex w-px flex-none flex-col items-center self-stretch bg-surface-neutral-tertiary mobile:hidden" />
|
||||
<div className="flex w-80 flex-none flex-col items-start gap-2 mobile:w-full">
|
||||
<div className="bg-surface-neutral-tertiary mobile:hidden flex w-px flex-none flex-col items-center self-stretch" />
|
||||
<div className="mobile:w-full flex w-80 flex-none flex-col items-start gap-2">
|
||||
<span className="text-body-small-semibold-150 font-body-small-semibold-150 text-text-neutral-tertiary">
|
||||
{t("settings.profile.security.accountSecurity")}
|
||||
</span>
|
||||
<div className="flex w-full items-center gap-3 rounded-md bg-surface-neutral-primary px-3 py-2">
|
||||
<div className="bg-surface-neutral-primary flex w-full items-center gap-3 rounded-md px-3 py-2">
|
||||
<FeatherShieldCheck
|
||||
className={
|
||||
"text-body-default-regular-0 font-body-default-regular-0 " +
|
||||
(mfaEnabled ? "text-icon-feedback-positive" : "text-icon-neutral-tertiary")
|
||||
"text-body-default-regular-0 font-body-default-regular-0 " + (mfaEnabled ? "text-icon-feedback-positive" : "text-icon-neutral-tertiary")
|
||||
}
|
||||
/>
|
||||
<div className="flex grow shrink-0 basis-0 flex-col items-start">
|
||||
<div className="flex shrink-0 grow basis-0 flex-col items-start">
|
||||
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary">
|
||||
{t("settings.profile.security.twoFactorShort")}
|
||||
</span>
|
||||
@@ -279,11 +287,11 @@ export default function MyProfileScreen({
|
||||
</div>
|
||||
|
||||
{/* Reihe 2 — Basis info + Login info */}
|
||||
<div className="flex w-full items-start gap-4 mobile:flex-col">
|
||||
<div className="mobile:flex-col flex w-full items-start gap-4">
|
||||
<NeutralCard>
|
||||
<span className="text-heading- font-heading- text-text-neutral-primary">{t("settings.profile.basicInfo.title")}</span>
|
||||
<CardDivider />
|
||||
<Form method="post" replace className="flex w-full flex-col items-start gap-3">
|
||||
<Form method="post" replace className="flex w-full flex-col items-start gap-3" data-ui-id="ui.settings.profile.form">
|
||||
<input type="hidden" name="csrf" value={csrf} readOnly />
|
||||
<input type="hidden" name="action" value="profile" readOnly />
|
||||
{/* Avatar mitsenden, damit Speichern des Namens das vorhandene Bild nicht löscht. */}
|
||||
@@ -293,6 +301,7 @@ export default function MyProfileScreen({
|
||||
<TextInput.Input
|
||||
name="firstName"
|
||||
required
|
||||
aria-label={t("models.user.firstName")}
|
||||
defaultValue={user.firstName ?? ""}
|
||||
placeholder={t("account.shared.firstNamePlaceholder")}
|
||||
data-ui-id="ui.settings.profile.firstName"
|
||||
@@ -304,6 +313,7 @@ export default function MyProfileScreen({
|
||||
<TextInput className="h-auto w-56 flex-none">
|
||||
<TextInput.Input
|
||||
name="lastName"
|
||||
aria-label={t("models.user.lastName")}
|
||||
defaultValue={user.lastName ?? ""}
|
||||
placeholder={t("account.shared.lastNamePlaceholder")}
|
||||
data-ui-id="ui.settings.profile.lastName"
|
||||
@@ -313,7 +323,14 @@ export default function MyProfileScreen({
|
||||
<CardDivider />
|
||||
<SettingRow label={t("settings.profile.basicInfo.phone")}>
|
||||
<TextInput disabled className="h-auto w-56 flex-none" type="tel">
|
||||
<TextInput.Input type="tel" disabled readOnly value={user.phone ?? ""} data-ui-id="ui.settings.profile.phone" />
|
||||
<TextInput.Input
|
||||
type="tel"
|
||||
disabled
|
||||
readOnly
|
||||
aria-label={t("settings.profile.basicInfo.phone")}
|
||||
value={user.phone ?? ""}
|
||||
data-ui-id="ui.settings.profile.phone"
|
||||
/>
|
||||
</TextInput>
|
||||
</SettingRow>
|
||||
<CardDivider />
|
||||
@@ -322,13 +339,21 @@ export default function MyProfileScreen({
|
||||
disabled
|
||||
className="h-auto w-56 flex-none"
|
||||
placeholder={t("settings.profile.basicInfo.department")}
|
||||
triggerAriaLabel={t("settings.profile.basicInfo.department")}
|
||||
data-ui-id="ui.settings.profile.department"
|
||||
/>
|
||||
</SettingRow>
|
||||
<CardDivider />
|
||||
<SettingRow label={t("models.user.role")} helpText={t("settings.profile.basicInfo.roleAssignedByAdmin")}>
|
||||
<TextInput disabled className="h-auto w-56 flex-none">
|
||||
<TextInput.Input disabled readOnly value={roleLabel} placeholder={t("models.user.role")} data-ui-id="ui.settings.profile.role" />
|
||||
<TextInput.Input
|
||||
disabled
|
||||
readOnly
|
||||
aria-label={t("models.user.role")}
|
||||
value={roleLabel}
|
||||
placeholder={t("models.user.role")}
|
||||
data-ui-id="ui.settings.profile.role"
|
||||
/>
|
||||
</TextInput>
|
||||
</SettingRow>
|
||||
<div className="flex w-full items-center justify-end">
|
||||
@@ -345,15 +370,20 @@ export default function MyProfileScreen({
|
||||
<CardDivider />
|
||||
<SettingRow label={t("settings.profile.loginInfo.email")}>
|
||||
<TextInput disabled className="h-auto w-72 flex-none" type="email">
|
||||
<TextInput.Input type="email" disabled readOnly value={user.email} data-ui-id="ui.settings.profile.email" />
|
||||
<TextInput.Input
|
||||
type="email"
|
||||
disabled
|
||||
readOnly
|
||||
aria-label={t("settings.profile.loginInfo.email")}
|
||||
value={user.email}
|
||||
data-ui-id="ui.settings.profile.email"
|
||||
/>
|
||||
</TextInput>
|
||||
</SettingRow>
|
||||
<CardDivider />
|
||||
<SettingRow label={t("settings.profile.password")}>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary tracking-widest">
|
||||
••••••••••
|
||||
</span>
|
||||
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary tracking-widest">••••••••••</span>
|
||||
<Button size="small" onClick={() => setPwOpen(true)} data-ui-id="ui.settings.profile.password.open">
|
||||
{t("settings.profile.changePassword")}
|
||||
</Button>
|
||||
@@ -374,6 +404,9 @@ export default function MyProfileScreen({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{cropSource ? (
|
||||
<AvatarCropDialog source={cropSource} submitting={submitting} onCancel={() => setCropSource(null)} onConfirm={onCropConfirmed} />
|
||||
) : null}
|
||||
{pwOpen ? (
|
||||
actionData?.passwordLocked ? (
|
||||
<ChangePasswordLockedDialog retryLabel={actionData.passwordLockedRetryLabel} onClose={() => setPwOpen(false)} />
|
||||
@@ -398,17 +431,27 @@ export default function MyProfileScreen({
|
||||
);
|
||||
}
|
||||
|
||||
function ModalShell({ children, dataUiId, center = false }: { children: React.ReactNode; dataUiId: string; center?: boolean }) {
|
||||
function ModalShell({
|
||||
children,
|
||||
dataUiId,
|
||||
center = false,
|
||||
onClose,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
dataUiId: string;
|
||||
center?: boolean;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex flex-col items-center justify-center gap-2 bg-surface-neutral-overlay px-4 py-4" data-ui-id={dataUiId}>
|
||||
<DialogOverlay dataUiId={dataUiId} onClose={onClose}>
|
||||
<div
|
||||
className={`flex w-full max-w-[480px] flex-col gap-6 rounded-md border border-solid border-border-default bg-surface-neutral-modal px-6 py-6 shadow-lg mobile:max-w-full ${
|
||||
className={`border-border-default bg-surface-neutral-modal mobile:max-w-full flex w-full max-w-[480px] flex-col gap-6 rounded-md border border-solid px-6 py-6 shadow-lg ${
|
||||
center ? "items-center text-center" : "items-start"
|
||||
}`}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</DialogOverlay>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -443,32 +486,37 @@ function ChangePasswordDialog({
|
||||
const strength = passwordStrength(pw);
|
||||
const fullName = [user.firstName, user.lastName].filter(Boolean).join(" ");
|
||||
return (
|
||||
<DialogOverlay dataUiId="ui.settings.profile.password.modal">
|
||||
<div className="flex w-full flex-col items-start gap-6 rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-6 py-6 shadow-lg max-w-[480px] relative mobile:px-4 mobile:py-5">
|
||||
<DialogOverlay dataUiId="ui.settings.profile.password.modal" onClose={onClose}>
|
||||
<div className="border-border-default bg-surface-neutral-secondary mobile:px-4 mobile:py-5 relative flex w-full max-w-[480px] flex-col items-start gap-6 rounded-lg border border-solid px-6 py-6 shadow-lg">
|
||||
<IconButton
|
||||
className="absolute right-3 top-3"
|
||||
className="absolute top-3 right-3"
|
||||
variant="ghost"
|
||||
size="small"
|
||||
icon={<FeatherX />}
|
||||
aria-label={t("shared.close")}
|
||||
onClick={onClose}
|
||||
data-ui-id="ui.settings.profile.password.close"
|
||||
/>
|
||||
<div className="flex w-full flex-col items-center justify-center gap-1">
|
||||
<div className="flex h-11 w-11 flex-none items-center justify-center rounded-round bg-surface-feedback-subtle-information">
|
||||
<div className="rounded-round bg-surface-feedback-subtle-information flex h-11 w-11 flex-none items-center justify-center">
|
||||
<FeatherShieldCheck className="text-heading- font-heading- text-icon-feedback-information" />
|
||||
</div>
|
||||
<span className="w-full text-heading- font-heading- text-text-neutral-primary text-center">{t("settings.profile.reauth.title")}</span>
|
||||
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary text-center">
|
||||
<span className="text-heading- font-heading- text-text-neutral-primary w-full text-center">{t("settings.profile.reauth.title")}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary w-full text-center">
|
||||
{t("settings.profile.reauth.subtitle")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex w-full items-center gap-3 rounded-md border border-solid border-border-default bg-surface-neutral-secondary px-4 py-3">
|
||||
<Avatar size="medium" image={user.avatar ?? undefined}>{initials(user)}</Avatar>
|
||||
<div className="flex grow shrink-0 basis-0 flex-col items-start">
|
||||
<span className="w-full text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary">{fullName || user.email}</span>
|
||||
<span className="w-full text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">{user.email}</span>
|
||||
<div className="border-border-default bg-surface-neutral-secondary flex w-full items-center gap-3 rounded-md border border-solid px-4 py-3">
|
||||
<Avatar size="medium" image={user.avatar ?? undefined}>
|
||||
{initials(user)}
|
||||
</Avatar>
|
||||
<div className="flex shrink-0 grow basis-0 flex-col items-start">
|
||||
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary w-full">{fullName || user.email}</span>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary w-full">{user.email}</span>
|
||||
</div>
|
||||
<BadgeFeedback farbe="subtle-neutral" size="small">{t("settings.profile.reauth.currentAccount")}</BadgeFeedback>
|
||||
<BadgeFeedback farbe="subtle-neutral" size="small">
|
||||
{t("settings.profile.reauth.currentAccount")}
|
||||
</BadgeFeedback>
|
||||
</div>
|
||||
<Form method="post" replace className="flex w-full flex-col items-start gap-6">
|
||||
<input type="hidden" name="csrf" value={csrf} readOnly />
|
||||
@@ -495,18 +543,32 @@ function ChangePasswordDialog({
|
||||
data-ui-id="ui.settings.profile.password.new"
|
||||
/>
|
||||
</TextInput>
|
||||
<Progress className="h-auto w-full flex-none" hideLabel value={strength} state={strength >= 80 ? "success" : undefined} />
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">{t("settings.profile.passwordDialog.hint")}</span>
|
||||
<Progress
|
||||
className="h-auto w-full flex-none"
|
||||
hideLabel
|
||||
value={strength}
|
||||
state={strength >= 80 ? "success" : undefined}
|
||||
aria-label={t("settings.profile.passwordDialog.hint")}
|
||||
/>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("settings.profile.passwordDialog.hint")}
|
||||
</span>
|
||||
</div>
|
||||
<TextInput className="h-auto w-full flex-none" showLabel label={t("settings.profile.passwordDialog.confirm")} type="password">
|
||||
<TextInput.Input name="passwordNewConfirm" type="password" required autoComplete="new-password" data-ui-id="ui.settings.profile.password.confirm" />
|
||||
</TextInput>
|
||||
{error ? <span className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative">{error}</span> : null}
|
||||
<div className="flex w-full items-center justify-end gap-2 mobile:flex-col-reverse">
|
||||
<Button className="h-9 grow shrink-0 basis-0" type="button" variant="secondary" onClick={onClose} data-ui-id="ui.settings.profile.password.cancel">
|
||||
<div className="mobile:flex-col-reverse flex w-full items-center justify-end gap-2">
|
||||
<Button className="h-9 shrink-0 grow basis-0" type="button" variant="secondary" onClick={onClose} data-ui-id="ui.settings.profile.password.cancel">
|
||||
{t("shared.cancel")}
|
||||
</Button>
|
||||
<Button className="h-9 grow shrink-0 basis-0" type="submit" iconRight={<FeatherArrowRight />} loading={submitting} data-ui-id="ui.settings.profile.password.submit">
|
||||
<Button
|
||||
className="h-9 shrink-0 grow basis-0"
|
||||
type="submit"
|
||||
iconRight={<FeatherArrowRight />}
|
||||
loading={submitting}
|
||||
data-ui-id="ui.settings.profile.password.submit"
|
||||
>
|
||||
{t("settings.profile.mfa.setup.next")}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -519,13 +581,13 @@ function ChangePasswordDialog({
|
||||
function ChangePasswordLockedDialog({ retryLabel, onClose }: { retryLabel?: string; onClose: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<DialogOverlay dataUiId="ui.settings.profile.password.locked">
|
||||
<Card className="max-w-[480px] mobile:gap-6 mobile:shadow-lg mobile:px-4 mobile:py-5">
|
||||
<DialogOverlay dataUiId="ui.settings.profile.password.locked" onClose={onClose}>
|
||||
<Card className="mobile:gap-6 mobile:shadow-lg mobile:px-4 mobile:py-5 max-w-[480px]">
|
||||
<div className="flex w-full flex-col items-center gap-4">
|
||||
<IconWithBackground variant="warning" size="extra-large" round={true} icon={<FeatherShieldAlert />} />
|
||||
<div className="flex w-full flex-col items-center gap-1">
|
||||
<span className="w-full text-heading- font-heading- text-text-neutral-primary text-center">{t("settings.profile.changePasswordLocked.title")}</span>
|
||||
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary text-center">
|
||||
<span className="text-heading- font-heading- text-text-neutral-primary w-full text-center">{t("settings.profile.changePasswordLocked.title")}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary w-full text-center">
|
||||
{t("settings.profile.changePasswordLocked.subtitle")}
|
||||
</span>
|
||||
</div>
|
||||
@@ -555,15 +617,31 @@ function ChangePasswordLockedDialog({ retryLabel, onClose }: { retryLabel?: stri
|
||||
);
|
||||
}
|
||||
|
||||
function DialogOverlay({ children, dataUiId }: { children: React.ReactNode; dataUiId: string }) {
|
||||
// Entspricht Davids DialogLayout/Dialog-Overlay (zentrierte Card auf abgedunkeltem Hintergrund).
|
||||
function DialogOverlay({ children, dataUiId, onClose }: { children: React.ReactNode; dataUiId: string; onClose: () => void }) {
|
||||
// Davids DialogLayout (zentrierte Card auf abgedunkeltem Hintergrund) — aber
|
||||
// durch die geteilte Dialog-Komponente, wie jeder andere Pop-up im Produkt.
|
||||
// Vorher war das ein handgebautes `fixed inset-0` mitten im Seiteninhalt: das
|
||||
// dunkelte nur den Inhaltsbereich ab, weil Sidebar und Kopfleiste auf
|
||||
// derselben z-Ebene darueber lagen, und brachte weder Fokus-Falle noch
|
||||
// Escape-to-close mit. Die Dialog-Komponente portalisiert nach document.body
|
||||
// und loest das strukturell.
|
||||
//
|
||||
// Dialog.Content bleibt hier bewusst transparent und randlos: die Karte
|
||||
// darin ist Davids Screen und bringt Rahmen, Flaeche und Schatten selbst mit.
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex flex-col items-center justify-center gap-2 bg-surface-neutral-overlay px-4 py-4"
|
||||
data-ui-id={dataUiId}
|
||||
<Dialog
|
||||
open
|
||||
onOpenChange={(open: boolean) => {
|
||||
if (!open) onClose();
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
<Dialog.Content
|
||||
className="max-h-[90vh] w-auto min-w-0 max-w-[92vw] overflow-auto border-none bg-transparent shadow-none"
|
||||
data-ui-id={dataUiId}
|
||||
>
|
||||
{children}
|
||||
</Dialog.Content>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -591,7 +669,7 @@ function TwoFaModal({
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const secret = otpauthUri ? new URLSearchParams(otpauthUri.split("?")[1] ?? "").get("secret") ?? "" : "";
|
||||
const secret = otpauthUri ? (new URLSearchParams(otpauthUri.split("?")[1] ?? "").get("secret") ?? "") : "";
|
||||
const groupedSecret = secret.replace(/(.{4})/g, "$1 ").trim();
|
||||
const [digits, setDigits] = useState<string[]>(Array(6).fill(""));
|
||||
const code = digits.join("");
|
||||
@@ -607,15 +685,15 @@ function TwoFaModal({
|
||||
if (step === "manage") {
|
||||
const activatedLabel =
|
||||
enabledAt != null
|
||||
? t("settings.profile.mfa.manage.activatedAt", { date: new Date(enabledAt).toLocaleDateString(i18n.language) })
|
||||
? t("settings.profile.mfa.manage.activatedAt", { date: formatDate(enabledAt, i18n.language) })
|
||||
: t("settings.profile.mfa.status.enabled");
|
||||
return (
|
||||
<DialogOverlay dataUiId="ui.settings.profile.mfa.manage.dialog">
|
||||
<div className="flex h-auto w-auto min-w-[384px] max-w-[576px] max-h-[90vh] flex-none flex-col items-start gap-2 overflow-auto rounded-md border border-solid border-border-default bg-surface-neutral-modal shadow-lg mobile:w-full mobile:min-w-0">
|
||||
<div className="flex w-full items-start gap-4 px-4 pt-4 mobile:pb-4">
|
||||
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-1">
|
||||
<span className="w-full text-heading- font-heading- text-text-neutral-primary">{t("settings.profile.mfa.title")}</span>
|
||||
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
<DialogOverlay dataUiId="ui.settings.profile.mfa.manage.dialog" onClose={onClose}>
|
||||
<div className="border-border-default bg-surface-neutral-modal mobile:w-full mobile:min-w-0 flex h-auto max-h-[90vh] w-auto max-w-[576px] min-w-[384px] flex-none flex-col items-start gap-2 overflow-auto rounded-md border border-solid shadow-lg">
|
||||
<div className="mobile:pb-4 flex w-full items-start gap-4 px-4 pt-4">
|
||||
<div className="flex shrink-0 grow basis-0 flex-col items-start gap-1">
|
||||
<span className="text-heading- font-heading- text-text-neutral-primary w-full">{t("settings.profile.mfa.title")}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary w-full">
|
||||
{t("settings.profile.mfa.manage.subtitle")}
|
||||
</span>
|
||||
</div>
|
||||
@@ -623,11 +701,13 @@ function TwoFaModal({
|
||||
<IconButton variant="ghost" icon={<FeatherX />} onClick={onClose} data-ui-id="ui.settings.profile.mfa.manage.close" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex w-full flex-col items-start gap-3 px-4 pb-4 mobile:pt-4">
|
||||
<div className="flex w-full items-end justify-end gap-4 rounded-md border border-solid border-border-negative-subtle bg-surface-feedback-subtle-negative px-4 py-3 mobile:flex-col mobile:items-start mobile:justify-start mobile:gap-3">
|
||||
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-1">
|
||||
<span className="text-body-small-semibold-0 font-body-small-semibold-0 text-text-neutral-primary">{t("settings.profile.mfa.disable.title")}</span>
|
||||
<span className="w-full text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
|
||||
<div className="mobile:pt-4 flex w-full flex-col items-start gap-3 px-4 pb-4">
|
||||
<div className="border-border-negative-subtle bg-surface-feedback-subtle-negative mobile:flex-col mobile:items-start mobile:justify-start mobile:gap-3 flex w-full items-end justify-end gap-4 rounded-md border border-solid px-4 py-3">
|
||||
<div className="flex shrink-0 grow basis-0 flex-col items-start gap-1">
|
||||
<span className="text-body-small-semibold-0 font-body-small-semibold-0 text-text-neutral-primary">
|
||||
{t("settings.profile.mfa.disable.title")}
|
||||
</span>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary w-full">
|
||||
{t("settings.profile.mfa.manage.deactivateHint")}
|
||||
</span>
|
||||
</div>
|
||||
@@ -643,15 +723,17 @@ function TwoFaModal({
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex w-full flex-col items-start gap-1">
|
||||
<span className="text-body-extra-small-semibold-150 font-body-extra-small-semibold-150 uppercase tracking-wider text-text-neutral-tertiary">
|
||||
<span className="text-body-extra-small-semibold-150 font-body-extra-small-semibold-150 text-text-neutral-tertiary tracking-wider uppercase">
|
||||
{t("settings.profile.mfa.manage.methodsLabel")}
|
||||
</span>
|
||||
<div className="flex w-full flex-col items-start rounded-md border border-solid border-border-default bg-surface-neutral-secondary">
|
||||
<div className="flex w-full items-center gap-3 px-4 py-3 mobile:flex-col mobile:items-start">
|
||||
<div className="border-border-default bg-surface-neutral-secondary flex w-full flex-col items-start rounded-md border border-solid">
|
||||
<div className="mobile:flex-col mobile:items-start flex w-full items-center gap-3 px-4 py-3">
|
||||
<IconWithBackground variant="neutral" size="large" icon={<FeatherSmartphone />} />
|
||||
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-1">
|
||||
<div className="flex shrink-0 grow basis-0 flex-col items-start gap-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{t("settings.profile.mfa.authenticatorApp")}</span>
|
||||
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">
|
||||
{t("settings.profile.mfa.authenticatorApp")}
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">{activatedLabel}</span>
|
||||
</div>
|
||||
@@ -688,23 +770,29 @@ function TwoFaModal({
|
||||
|
||||
if (step === "success") {
|
||||
return (
|
||||
<ModalShell dataUiId="ui.settings.profile.mfa.success" center>
|
||||
<FeatherCheckCircle className="text-[48px] font-[400] text-icon-feedback-positive" />
|
||||
<ModalShell dataUiId="ui.settings.profile.mfa.success" center onClose={onClose}>
|
||||
<FeatherCheckCircle className="text-icon-feedback-positive text-[48px] font-[400]" />
|
||||
<div className="flex w-full flex-col items-center gap-2">
|
||||
<span className="text-heading- font-heading- text-text-neutral-primary">{t("settings.profile.mfa.success.title")}</span>
|
||||
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">{t("settings.profile.mfa.success.subtitle")}</span>
|
||||
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
|
||||
{t("settings.profile.mfa.success.subtitle")}
|
||||
</span>
|
||||
</div>
|
||||
{recoveryCodes && recoveryCodes.length > 0 ? (
|
||||
<div className="flex w-full flex-col items-start gap-2 rounded-md border border-solid border-border-default bg-surface-neutral-primary px-4 py-4">
|
||||
<div className="border-border-default bg-surface-neutral-primary flex w-full flex-col items-start gap-2 rounded-md border border-solid px-4 py-4">
|
||||
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-secondary">{t("settings.profile.mfa.recoveryCodes")}</span>
|
||||
<div className="grid w-full grid-cols-2 gap-1">
|
||||
{recoveryCodes.map((code) => (
|
||||
<span key={code} className="font-mono text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-primary">{code}</span>
|
||||
<span key={code} className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-primary font-mono">
|
||||
{code}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
<Button className="h-10 w-full flex-none" variant="primary" onClick={onClose} data-ui-id="ui.settings.profile.mfa.done">{t("settings.profile.mfa.success.done")}</Button>
|
||||
<Button className="h-10 w-full flex-none" variant="primary" onClick={onClose} data-ui-id="ui.settings.profile.mfa.done">
|
||||
{t("settings.profile.mfa.success.done")}
|
||||
</Button>
|
||||
</ModalShell>
|
||||
);
|
||||
}
|
||||
@@ -713,22 +801,22 @@ function TwoFaModal({
|
||||
// (Der Passwort-Gate-Step "password" läuft davor, da startTotpEnrollment das aktuelle Passwort verlangt.)
|
||||
if (step === "qr") {
|
||||
return (
|
||||
<DialogOverlay dataUiId="ui.settings.profile.mfa.setup">
|
||||
<DialogOverlay dataUiId="ui.settings.profile.mfa.setup" onClose={onClose}>
|
||||
<Card
|
||||
className="h-auto w-auto min-w-[384px] max-w-[576px] max-h-[90vh] overflow-auto mobile:w-full mobile:min-w-0 mobile:px-4 mobile:py-4 mobile:shadow-lg"
|
||||
className="mobile:w-full mobile:min-w-0 mobile:px-4 mobile:py-4 mobile:shadow-lg h-auto max-h-[90vh] w-auto max-w-[576px] min-w-[384px] overflow-auto"
|
||||
size="large"
|
||||
>
|
||||
<div className="flex w-full items-start justify-between">
|
||||
<div className="flex grow shrink-0 basis-0 flex-col items-center gap-1">
|
||||
<div className="flex shrink-0 grow basis-0 flex-col items-center gap-1">
|
||||
<span className="text-heading- font-heading- text-text-neutral-primary text-center">{t("settings.profile.mfa.manage.addDevice")}</span>
|
||||
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary text-center">
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary w-full text-center">
|
||||
{t("settings.profile.mfa.add.subtitle")}
|
||||
</span>
|
||||
</div>
|
||||
<IconButton variant="ghost" size="small" icon={<FeatherX />} onClick={onClose} data-ui-id="ui.settings.profile.mfa.setup.close" />
|
||||
</div>
|
||||
<div className="flex w-full flex-col items-center gap-2">
|
||||
<div className="flex h-44 w-44 flex-none items-center justify-center rounded-md border border-solid border-border-default bg-surface-neutral-secondary px-2 py-2">
|
||||
<div className="border-border-default bg-surface-neutral-secondary flex h-44 w-44 flex-none items-center justify-center rounded-md border border-solid px-2 py-2">
|
||||
{otpauthUri ? <QRCodeSVG className="h-40 w-40 flex-none" value={otpauthUri} size={160} /> : null}
|
||||
</div>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary text-center">
|
||||
@@ -738,13 +826,21 @@ function TwoFaModal({
|
||||
{secret ? (
|
||||
<>
|
||||
<div className="flex w-full items-center gap-2.5">
|
||||
<div className="flex h-px grow shrink-0 basis-0 flex-col items-center bg-border-default" />
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">{t("settings.profile.mfa.setup.manualKey")}</span>
|
||||
<div className="flex h-px grow shrink-0 basis-0 flex-col items-center bg-border-default" />
|
||||
<div className="bg-border-default flex h-px shrink-0 grow basis-0 flex-col items-center" />
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("settings.profile.mfa.setup.manualKey")}
|
||||
</span>
|
||||
<div className="bg-border-default flex h-px shrink-0 grow basis-0 flex-col items-center" />
|
||||
</div>
|
||||
<div className="flex w-full items-center justify-between rounded-md border border-solid border-border-default bg-surface-neutral-secondary px-1 py-1">
|
||||
<span className="grow shrink-0 basis-0 text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary text-center">{groupedSecret}</span>
|
||||
<CopyToClipboardButton clipboardText={secret} tooltipText={t("settings.profile.mfa.add.copyKey")} />
|
||||
<div className="border-border-default bg-surface-neutral-secondary flex w-full items-center justify-between rounded-md border border-solid px-1 py-1">
|
||||
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary shrink-0 grow basis-0 text-center">
|
||||
{groupedSecret}
|
||||
</span>
|
||||
<CopyToClipboardButton
|
||||
clipboardText={secret}
|
||||
tooltipText={t("settings.profile.mfa.add.copyKey")}
|
||||
successKey="settings.profile.mfa.add.keyCopied"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
@@ -753,7 +849,9 @@ function TwoFaModal({
|
||||
<input type="hidden" name="action" value="confirmTotpEnrollment" readOnly />
|
||||
<input type="hidden" name="code" value={code} readOnly />
|
||||
<div className="flex w-full flex-col items-center gap-2">
|
||||
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-secondary text-center">{t("settings.profile.mfa.add.codeLabel")}</span>
|
||||
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-secondary text-center">
|
||||
{t("settings.profile.mfa.add.codeLabel")}
|
||||
</span>
|
||||
<div className="flex w-full flex-col items-center gap-2 px-1 py-1">
|
||||
<InputOtp state={mfaError ? "error" : "default"} title="" helperText={mfaError ?? ""}>
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
@@ -771,7 +869,7 @@ function TwoFaModal({
|
||||
</InputOtp>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex w-full items-center justify-end gap-2 mobile:flex-col-reverse">
|
||||
<div className="mobile:flex-col-reverse flex w-full items-center justify-end gap-2">
|
||||
<Button type="button" className="mobile:w-full" variant="secondary" onClick={onClose} data-ui-id="ui.settings.profile.mfa.setup.cancel">
|
||||
{t("shared.cancel")}
|
||||
</Button>
|
||||
@@ -796,38 +894,51 @@ function TwoFaModal({
|
||||
// das bestehende disableTotpEnrollment verifiziert das Passwort -> Bestätigung bleibt Passwort-basiert.
|
||||
if (step === "disable") {
|
||||
return (
|
||||
<DialogOverlay dataUiId="ui.settings.profile.mfa.disable">
|
||||
<Card className="w-full max-w-[480px] max-h-[90vh] overflow-auto mobile:gap-6 mobile:px-4 mobile:py-5 mobile:shadow-lg">
|
||||
<DialogOverlay dataUiId="ui.settings.profile.mfa.disable" onClose={onClose}>
|
||||
<Card className="mobile:gap-6 mobile:px-4 mobile:py-5 mobile:shadow-lg max-h-[90vh] w-full max-w-[480px] overflow-auto">
|
||||
<div className="flex w-full flex-col items-center justify-center gap-1">
|
||||
<IconWithBackground variant="destructive" size="large" round={true} icon={<FeatherShieldOff />} />
|
||||
<span className="w-full text-heading- font-heading- text-text-neutral-primary text-center">{t("settings.profile.mfa.deactivate.title")}</span>
|
||||
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary text-center">
|
||||
<span className="text-heading- font-heading- text-text-neutral-primary w-full text-center">{t("settings.profile.mfa.deactivate.title")}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary w-full text-center">
|
||||
{t("settings.profile.mfa.deactivate.subtitle")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex w-full flex-col items-center justify-center gap-2 rounded-md border border-solid border-border-negative-subtle bg-surface-feedback-subtle-negative px-4 py-3">
|
||||
<div className="border-border-negative-subtle bg-surface-feedback-subtle-negative flex w-full flex-col items-center justify-center gap-2 rounded-md border border-solid px-4 py-3">
|
||||
<div className="flex w-full items-center justify-center gap-2">
|
||||
<span className="grow shrink-0 basis-0 text-body-small-semibold-150 font-body-small-semibold-150 text-text-feedback-negative text-center">
|
||||
<span className="text-body-small-semibold-150 font-body-small-semibold-150 text-text-feedback-negative shrink-0 grow basis-0 text-center">
|
||||
{t("settings.profile.mfa.deactivate.consequencesTitle")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex w-full flex-col items-start gap-2">
|
||||
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">{t("settings.profile.mfa.deactivate.consequence1")}</span>
|
||||
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">{t("settings.profile.mfa.deactivate.consequence2")}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary w-full">
|
||||
{t("settings.profile.mfa.deactivate.consequence1")}
|
||||
</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary w-full">
|
||||
{t("settings.profile.mfa.deactivate.consequence2")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<Form method="post" replace className="contents">
|
||||
<input type="hidden" name="csrf" value={csrf} readOnly />
|
||||
<input type="hidden" name="action" value="disableTotpEnrollment" readOnly />
|
||||
<div className="flex w-full flex-col items-center justify-center gap-2">
|
||||
<span className="text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-secondary">{t("settings.profile.passwordDialog.current")}</span>
|
||||
<span className="text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-secondary">
|
||||
{t("settings.profile.passwordDialog.current")}
|
||||
</span>
|
||||
<TextInput className="h-auto w-full flex-none" type="password">
|
||||
<TextInput.Input name="passwordCurrent" type="password" required autoFocus autoComplete="current-password" data-ui-id="ui.settings.profile.mfa.disablePassword" />
|
||||
<TextInput.Input
|
||||
name="passwordCurrent"
|
||||
type="password"
|
||||
required
|
||||
autoFocus
|
||||
autoComplete="current-password"
|
||||
data-ui-id="ui.settings.profile.mfa.disablePassword"
|
||||
/>
|
||||
</TextInput>
|
||||
{mfaError ? <span className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative">{mfaError}</span> : null}
|
||||
</div>
|
||||
<div className="flex h-px w-full flex-none flex-col items-center bg-border-default" />
|
||||
<div className="flex w-full items-center justify-end gap-2 mobile:flex-col-reverse">
|
||||
<div className="bg-border-default flex h-px w-full flex-none flex-col items-center" />
|
||||
<div className="mobile:flex-col-reverse flex w-full items-center justify-end gap-2">
|
||||
<Button type="button" className="mobile:w-full" variant="secondary" onClick={onClose} data-ui-id="ui.settings.profile.mfa.disableCancel">
|
||||
{t("shared.cancel")}
|
||||
</Button>
|
||||
@@ -850,10 +961,12 @@ function TwoFaModal({
|
||||
|
||||
// step === "password" — Setup-Gate (Action verlangt aktuelles Passwort, bevor der QR erzeugt wird)
|
||||
return (
|
||||
<ModalShell dataUiId="ui.settings.profile.mfa.gate">
|
||||
<ModalShell dataUiId="ui.settings.profile.mfa.gate" onClose={onClose}>
|
||||
<div className="flex w-full flex-col items-start gap-2">
|
||||
<span className="text-heading- font-heading- text-text-neutral-primary">{t("settings.profile.mfa.setup.title")}</span>
|
||||
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">{t("settings.profile.mfa.gate.subtitle")}</span>
|
||||
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
|
||||
{t("settings.profile.mfa.gate.subtitle")}
|
||||
</span>
|
||||
</div>
|
||||
<Form method="post" replace className="flex w-full flex-col items-start gap-4">
|
||||
<input type="hidden" name="csrf" value={csrf} readOnly />
|
||||
@@ -862,9 +975,13 @@ function TwoFaModal({
|
||||
<TextInput.Input name="passwordCurrent" type="password" required autoComplete="current-password" data-ui-id="ui.settings.profile.mfa.gatePassword" />
|
||||
</TextInput>
|
||||
{mfaError ? <span className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative">{mfaError}</span> : null}
|
||||
<div className="flex w-full items-center justify-end gap-2 mobile:flex-col-reverse mobile:items-stretch">
|
||||
<Button type="button" variant="tertiary" onClick={onClose}>{t("shared.cancel")}</Button>
|
||||
<Button type="submit" variant="primary" loading={submitting} data-ui-id="ui.settings.profile.mfa.gateSubmit">{t("settings.profile.mfa.setup.next")}</Button>
|
||||
<div className="mobile:flex-col-reverse mobile:items-stretch flex w-full items-center justify-end gap-2">
|
||||
<Button type="button" variant="tertiary" onClick={onClose}>
|
||||
{t("shared.cancel")}
|
||||
</Button>
|
||||
<Button type="submit" variant="primary" loading={submitting} data-ui-id="ui.settings.profile.mfa.gateSubmit">
|
||||
{t("settings.profile.mfa.setup.next")}
|
||||
</Button>
|
||||
</div>
|
||||
</Form>
|
||||
</ModalShell>
|
||||
|
||||
+303
@@ -0,0 +1,303 @@
|
||||
// @vitest-environment jsdom
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import RegisterScreen, { type RegistrationPlanOptionData } from "./RegisterScreen";
|
||||
|
||||
const rootDataState = vi.hoisted(() => ({ requireEmailVerification: true }));
|
||||
|
||||
globalThis.ResizeObserver =
|
||||
globalThis.ResizeObserver ??
|
||||
class ResizeObserver {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
};
|
||||
|
||||
vi.mock("react-router", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("react-router")>();
|
||||
return {
|
||||
...actual,
|
||||
Form: React.forwardRef<HTMLFormElement, React.FormHTMLAttributes<HTMLFormElement>>(function TestForm({ children, ...props }, ref) {
|
||||
return (
|
||||
<form ref={ref} {...props}>
|
||||
{children}
|
||||
</form>
|
||||
);
|
||||
}),
|
||||
Link: ({ children, to, ...props }: React.AnchorHTMLAttributes<HTMLAnchorElement> & { to: string }) => (
|
||||
<a href={to} {...props}>
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
useNavigate: () => vi.fn(),
|
||||
useNavigation: () => ({ state: "idle" }),
|
||||
useSearchParams: () => [new URLSearchParams()],
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useRootData", () => ({
|
||||
useRootData: () => ({
|
||||
csrf: "csrf-token",
|
||||
appConfiguration: {
|
||||
auth: {
|
||||
requireEmailVerification: rootDataState.requireEmailVerification,
|
||||
requireOrganization: true,
|
||||
requireName: true,
|
||||
authMethods: { emailPassword: { enabled: true } },
|
||||
captcha: { enabled: true, provider: "cap" },
|
||||
},
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/captcha/Captcha", () => ({
|
||||
default: ({ onStatusChange }: { onStatusChange?: (status: "pending" | "solved" | "error") => void }) => {
|
||||
React.useEffect(() => onStatusChange?.("pending"), [onStatusChange]);
|
||||
return (
|
||||
<button type="button" data-ui-id="ui.captcha.mount" aria-label="captcha" onClick={() => onStatusChange?.("solved")}>
|
||||
captcha
|
||||
</button>
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
const core: RegistrationPlanOptionData = {
|
||||
planId: "product_starter",
|
||||
planCode: "starter",
|
||||
titleKey: "Core",
|
||||
descriptionKey: "Core plan",
|
||||
priceId: "price_starter",
|
||||
amountCents: 19_900,
|
||||
baseAmountCents: 19_900,
|
||||
currency: "EUR",
|
||||
billingPeriod: 3,
|
||||
includedOfficeSeatQuantity: 2,
|
||||
includedFieldSeatQuantity: 5,
|
||||
includedStorageGb: 100,
|
||||
storagePerAdditionalSeatGb: 10,
|
||||
extraOfficeSeatQuantity: 0,
|
||||
extraFieldSeatQuantity: 0,
|
||||
recommended: true,
|
||||
};
|
||||
|
||||
const swarm: RegistrationPlanOptionData = {
|
||||
...core,
|
||||
planId: "product_pro",
|
||||
planCode: "pro",
|
||||
titleKey: "Swarm",
|
||||
descriptionKey: "Swarm plan",
|
||||
priceId: "price_pro",
|
||||
amountCents: 49_900,
|
||||
baseAmountCents: 49_900,
|
||||
includedOfficeSeatQuantity: 5,
|
||||
includedFieldSeatQuantity: 15,
|
||||
includedStorageGb: 500,
|
||||
storagePerAdditionalSeatGb: 20,
|
||||
recommended: true,
|
||||
};
|
||||
|
||||
describe("RegisterScreen plan advisor", () => {
|
||||
beforeEach(() => {
|
||||
rootDataState.requireEmailVerification = true;
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = new URL(String(input), "https://app.example.test");
|
||||
const largeTeam = url.searchParams.get("office") === "5" && url.searchParams.get("field") === "15";
|
||||
return Response.json(
|
||||
largeTeam
|
||||
? {
|
||||
plans: [{ ...core, amountCents: 62_600, extraOfficeSeatQuantity: 3, extraFieldSeatQuantity: 10, recommended: false }, swarm],
|
||||
selectedPriceId: "price_pro",
|
||||
recommendedPriceId: "price_pro",
|
||||
officeSeatQuantity: 5,
|
||||
fieldSeatQuantity: 15,
|
||||
}
|
||||
: {
|
||||
plans: [core, { ...swarm, recommended: false }],
|
||||
selectedPriceId: "price_starter",
|
||||
recommendedPriceId: "price_starter",
|
||||
officeSeatQuantity: 1,
|
||||
fieldSeatQuantity: 0,
|
||||
}
|
||||
);
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("blocks the plan step until every visible password requirement is met", () => {
|
||||
rootDataState.requireEmailVerification = false;
|
||||
const { container } = render(
|
||||
<RegisterScreen
|
||||
creationRequestKey="d7077797-054b-497a-b1ce-8e4f36257a96"
|
||||
subscriptionPlans={[core, { ...swarm, recommended: false }]}
|
||||
selectedSubscriptionPriceId="price_starter"
|
||||
recommendedSubscriptionPriceId="price_starter"
|
||||
initialOfficeSeatQuantity={1}
|
||||
initialFieldSeatQuantity={0}
|
||||
passwordPolicy={{ minLength: 12, requireUpper: true, requireLower: true, requireDigit: true, requireSpecial: true }}
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.change(container.querySelector('input[name="email"]')!, { target: { value: "ada@example.test" } });
|
||||
fireEvent.change(container.querySelector('input[name="password"]')!, { target: { value: "TooShort1!" } });
|
||||
fireEvent.change(container.querySelector('input[name="first-name"]')!, { target: { value: "Ada" } });
|
||||
fireEvent.change(container.querySelector('input[name="last-name"]')!, { target: { value: "Lovelace" } });
|
||||
fireEvent.change(container.querySelector('input[name="company"]')!, { target: { value: "Analytical Engines" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "account.register.continueToTeam" }));
|
||||
|
||||
expect(container.querySelector('[data-ui-id="ui.auth.register.accountStep"]')).not.toHaveClass("hidden");
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("account.register.passwordRequirements.fixBeforeContinue");
|
||||
expect(container.querySelector('input[name="password"]')).toHaveFocus();
|
||||
|
||||
fireEvent.change(container.querySelector('input[name="password"]')!, { target: { value: "ValidPassword1!" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "account.register.continueToTeam" }));
|
||||
|
||||
expect(container.querySelector('[data-ui-id="ui.auth.register.planStep"]')).not.toHaveClass("hidden");
|
||||
expect(container.querySelector('[data-ui-id="ui.auth.register.teamStep"]')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("moves account data to a separate team step and applies the server recommendation", async () => {
|
||||
const { container } = render(
|
||||
<RegisterScreen
|
||||
requireCaptcha
|
||||
creationRequestKey="d7077797-054b-497a-b1ce-8e4f36257a96"
|
||||
subscriptionPlans={[core, { ...swarm, recommended: false }]}
|
||||
selectedSubscriptionPriceId="price_starter"
|
||||
recommendedSubscriptionPriceId="price_starter"
|
||||
initialOfficeSeatQuantity={1}
|
||||
initialFieldSeatQuantity={0}
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.change(container.querySelector('input[name="email"]')!, { target: { value: "ada@example.test" } });
|
||||
fireEvent.change(container.querySelector('input[name="first-name"]')!, { target: { value: "Ada" } });
|
||||
fireEvent.change(container.querySelector('input[name="last-name"]')!, { target: { value: "Lovelace" } });
|
||||
fireEvent.change(container.querySelector('input[name="company"]')!, { target: { value: "Analytical Engines" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "account.register.continueToTeam" }));
|
||||
|
||||
expect(container.querySelector('[data-ui-id="ui.auth.register.planStep"]')).not.toHaveClass("hidden");
|
||||
expect(screen.queryByText("account.register.paymentStepLabel")).not.toBeInTheDocument();
|
||||
fireEvent.change(container.querySelector('input[name="selectedOfficeSeatQuantity"]')!, { target: { value: "5" } });
|
||||
fireEvent.change(container.querySelector('input[name="selectedFieldSeatQuantity"]')!, { target: { value: "15" } });
|
||||
|
||||
await waitFor(() => expect(container.querySelector('input[name="selectedSubscriptionPriceId"]')).toHaveValue("price_pro"));
|
||||
fireEvent.click(screen.getByRole("button", { name: "account.register.continueToPlans" }));
|
||||
expect(screen.getByText("Swarm")).toBeInTheDocument();
|
||||
expect(screen.getByText("account.register.recommendedBadge")).toBeInTheDocument();
|
||||
const finalPayload = new FormData(container.querySelector("form")!);
|
||||
expect(finalPayload.get("selectedOfficeSeatQuantity")).toBe("5");
|
||||
expect(finalPayload.get("selectedFieldSeatQuantity")).toBe("15");
|
||||
|
||||
fireEvent.click(screen.getByRole("radio", { name: /Core/u }));
|
||||
expect(container.querySelector('input[name="selectedSubscriptionPriceId"]')).toHaveValue("price_starter");
|
||||
fireEvent.click(screen.getByRole("button", { name: "account.register.backToTeam" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "account.register.backToAccount" }));
|
||||
expect(container.querySelector('[data-ui-id="ui.auth.register.accountStep"]')).not.toHaveClass("hidden");
|
||||
expect(container.querySelector('input[name="company"]')).toHaveValue("Analytical Engines");
|
||||
fireEvent.click(screen.getByRole("button", { name: "account.register.continueToTeam" }));
|
||||
expect(container.querySelector('input[name="selectedOfficeSeatQuantity"]')).toHaveValue(5);
|
||||
expect(container.querySelector('input[name="selectedFieldSeatQuantity"]')).toHaveValue(15);
|
||||
expect(container.querySelector('input[name="selectedSubscriptionPriceId"]')).toHaveValue("price_starter");
|
||||
});
|
||||
|
||||
it("keeps an explicit deep-linked plan through the initial recommendation refresh", async () => {
|
||||
const { container } = render(
|
||||
<RegisterScreen
|
||||
creationRequestKey="d7077797-054b-497a-b1ce-8e4f36257a96"
|
||||
subscriptionPlans={[core, { ...swarm, recommended: false }]}
|
||||
selectedSubscriptionPriceId="price_pro"
|
||||
recommendedSubscriptionPriceId="price_starter"
|
||||
initialOfficeSeatQuantity={1}
|
||||
initialFieldSeatQuantity={0}
|
||||
/>
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
});
|
||||
expect(fetch).toHaveBeenCalled();
|
||||
expect(container.querySelector('input[name="selectedSubscriptionPriceId"]')).toHaveValue("price_pro");
|
||||
});
|
||||
|
||||
it("offers an explicit retry when plan advice fails without trapping the team step", async () => {
|
||||
const fetchMock = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 503 }))
|
||||
.mockResolvedValueOnce(
|
||||
Response.json({
|
||||
plans: [core, { ...swarm, recommended: false }],
|
||||
selectedPriceId: "price_starter",
|
||||
recommendedPriceId: "price_starter",
|
||||
officeSeatQuantity: 1,
|
||||
fieldSeatQuantity: 0,
|
||||
})
|
||||
);
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const { container } = render(
|
||||
<RegisterScreen
|
||||
creationRequestKey="d7077797-054b-497a-b1ce-8e4f36257a96"
|
||||
subscriptionPlans={[core, { ...swarm, recommended: false }]}
|
||||
selectedSubscriptionPriceId="price_starter"
|
||||
recommendedSubscriptionPriceId="price_starter"
|
||||
initialOfficeSeatQuantity={1}
|
||||
initialFieldSeatQuantity={0}
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.change(container.querySelector('input[name="email"]')!, { target: { value: "ada@example.test" } });
|
||||
fireEvent.change(container.querySelector('input[name="first-name"]')!, { target: { value: "Ada" } });
|
||||
fireEvent.change(container.querySelector('input[name="last-name"]')!, { target: { value: "Lovelace" } });
|
||||
fireEvent.change(container.querySelector('input[name="company"]')!, { target: { value: "Analytical Engines" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "account.register.continueToTeam" }));
|
||||
await waitFor(() => expect(screen.getByText("account.register.recommendationErrorTitle")).toBeVisible());
|
||||
expect(screen.getByRole("button", { name: "account.register.continueToPlans" })).toBeDisabled();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "account.register.recommendationRetry" }));
|
||||
|
||||
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
|
||||
await waitFor(() => expect(screen.queryByText("account.register.recommendationErrorTitle")).not.toBeInTheDocument());
|
||||
expect(screen.getByRole("button", { name: "account.register.continueToPlans" })).toBeEnabled();
|
||||
});
|
||||
|
||||
it("requires a solved CAP proof and remounts a fresh challenge after a failed submit", () => {
|
||||
const props = {
|
||||
requireCaptcha: true,
|
||||
creationRequestKey: "d7077797-054b-497a-b1ce-8e4f36257a96",
|
||||
subscriptionPlans: [core, { ...swarm, recommended: false }],
|
||||
selectedSubscriptionPriceId: "price_starter",
|
||||
recommendedSubscriptionPriceId: "price_starter",
|
||||
initialOfficeSeatQuantity: 1,
|
||||
initialFieldSeatQuantity: 0,
|
||||
} as const;
|
||||
const { container, rerender } = render(<RegisterScreen {...props} />);
|
||||
|
||||
fireEvent.change(container.querySelector('input[name="email"]')!, { target: { value: "ada@example.test" } });
|
||||
fireEvent.change(container.querySelector('input[name="first-name"]')!, { target: { value: "Ada" } });
|
||||
fireEvent.change(container.querySelector('input[name="last-name"]')!, { target: { value: "Lovelace" } });
|
||||
fireEvent.change(container.querySelector('input[name="company"]')!, { target: { value: "Analytical Engines" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "account.register.continueToTeam" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "account.register.continueToPlans" }));
|
||||
|
||||
const submit = screen.getByRole("button", { name: "account.register.continueWithPlan" });
|
||||
fireEvent.click(screen.getByLabelText("account.register.consentTerms"));
|
||||
fireEvent.click(screen.getByLabelText("account.register.consentPrivacy"));
|
||||
expect(submit).toBeDisabled();
|
||||
|
||||
const firstCaptcha = screen.getByRole("button", { name: "captcha" });
|
||||
fireEvent.click(firstCaptcha);
|
||||
expect(submit).toBeEnabled();
|
||||
|
||||
rerender(<RegisterScreen {...props} error="account.register.errors.captchaFailed" captchaResetKey="retry-1" />);
|
||||
expect(screen.getByRole("button", { name: "account.register.continueWithPlan" })).toBeDisabled();
|
||||
expect(screen.getByRole("button", { name: "captcha" })).not.toBe(firstCaptcha);
|
||||
expect(screen.getByText("account.register.captchaReloadedTitle")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
// @vitest-environment jsdom
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import type React from "react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import RegisterScreen from "./RegisterScreen";
|
||||
|
||||
globalThis.ResizeObserver =
|
||||
globalThis.ResizeObserver ??
|
||||
class ResizeObserver {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
};
|
||||
|
||||
vi.mock("react-router", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("react-router")>();
|
||||
return {
|
||||
...actual,
|
||||
Form: ({ children, ...props }: React.FormHTMLAttributes<HTMLFormElement>) => <form {...props}>{children}</form>,
|
||||
Link: ({ children, to, ...props }: React.AnchorHTMLAttributes<HTMLAnchorElement> & { to: string }) => (
|
||||
<a href={to} {...props}>
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
useNavigate: () => vi.fn(),
|
||||
useNavigation: () => ({ state: "idle" }),
|
||||
useSearchParams: () => [new URLSearchParams()],
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useRootData", () => ({
|
||||
useRootData: () => ({
|
||||
csrf: "csrf-token",
|
||||
appConfiguration: {
|
||||
auth: {
|
||||
requireEmailVerification: true,
|
||||
requireOrganization: true,
|
||||
requireName: true,
|
||||
authMethods: { emailPassword: { enabled: true } },
|
||||
captcha: { enabled: false, provider: "mcaptcha" },
|
||||
},
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/captcha/Captcha", () => ({ default: () => null }));
|
||||
|
||||
const subscriptionPlans = [
|
||||
{
|
||||
planId: "product_starter",
|
||||
planCode: "starter",
|
||||
titleKey: "Core",
|
||||
descriptionKey: "Core plan",
|
||||
priceId: "price_starter",
|
||||
amountCents: 19_900,
|
||||
baseAmountCents: 19_900,
|
||||
currency: "EUR",
|
||||
billingPeriod: 3,
|
||||
includedOfficeSeatQuantity: 2,
|
||||
includedFieldSeatQuantity: 5,
|
||||
includedStorageGb: 100,
|
||||
storagePerAdditionalSeatGb: 10,
|
||||
extraOfficeSeatQuantity: 0,
|
||||
extraFieldSeatQuantity: 0,
|
||||
recommended: true,
|
||||
},
|
||||
] as const;
|
||||
|
||||
describe("RegisterScreen recovery state", () => {
|
||||
it("marks every configured organization and name field as required", () => {
|
||||
const { container } = render(
|
||||
<RegisterScreen
|
||||
creationRequestKey="d7077797-054b-497a-b1ce-8e4f36257a96"
|
||||
subscriptionPlans={subscriptionPlans}
|
||||
selectedSubscriptionPriceId="price_starter"
|
||||
recommendedSubscriptionPriceId="price_starter"
|
||||
initialOfficeSeatQuantity={1}
|
||||
initialFieldSeatQuantity={0}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(container.querySelector('input[name="company"]')).toBeRequired();
|
||||
expect(container.querySelector('input[name="first-name"]')).toBeRequired();
|
||||
expect(container.querySelector('input[name="last-name"]')).toBeRequired();
|
||||
expect(container.querySelector('input[name="selectedSubscriptionPriceId"]')).toHaveValue("price_starter");
|
||||
});
|
||||
|
||||
it("keeps the generic pending screen visible and renders resend errors in place", () => {
|
||||
const creationRequestKey = "d7077797-054b-497a-b1ce-8e4f36257a96";
|
||||
|
||||
const { container } = render(
|
||||
<RegisterScreen
|
||||
verificationEmailSent
|
||||
error="api.errors.tooManyRequests"
|
||||
data={{ email: "ada@example.test" }}
|
||||
creationRequestKey={creationRequestKey}
|
||||
subscriptionPlans={subscriptionPlans}
|
||||
selectedSubscriptionPriceId="price_starter"
|
||||
recommendedSubscriptionPriceId="price_starter"
|
||||
initialOfficeSeatQuantity={1}
|
||||
initialFieldSeatQuantity={0}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(container.querySelector('[data-ui-id="ui.auth.register.verificationSent"]')).toBeInTheDocument();
|
||||
expect(container.querySelector('[data-ui-id="ui.auth.register.form"]')).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("alert")).toHaveTextContent("api.errors.tooManyRequests");
|
||||
expect(container.querySelector('[data-ui-id="ui.auth.register.resendError"]')).toBeInTheDocument();
|
||||
expect(container.querySelector(`input[name="creationRequestKey"][value="${creationRequestKey}"]`)).toBeInTheDocument();
|
||||
expect(container.querySelector('input[name="selectedSubscriptionPriceId"]')).toHaveValue("price_starter");
|
||||
});
|
||||
});
|
||||
+342
-149
@@ -1,20 +1,20 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Form, Link, useNavigate, useNavigation, useSearchParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FeatherArrowLeft, FeatherBuilding, FeatherMail, FeatherMailCheck, FeatherPencil, FeatherRotateCw } from "@subframe/core";
|
||||
import { FeatherArrowLeft, FeatherBuilding, FeatherMailCheck, FeatherPencil, FeatherRotateCw } from "@subframe/core";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { AuthShell } from "~/components/auth/AuthShell";
|
||||
import { Alert } from "~/ui/components/Alert";
|
||||
import { Button } from "~/ui/components/Button";
|
||||
import { Card } from "~/ui/components/Card";
|
||||
import { Checkbox } from "~/ui/components/Checkbox";
|
||||
import { IconWithBackground } from "~/ui/components/IconWithBackground";
|
||||
import { LinkButton } from "~/ui/components/LinkButton";
|
||||
import { Logo } from "~/ui/components/Logo";
|
||||
import { Progress } from "~/ui/components/Progress";
|
||||
import { StepperHorizontal } from "~/ui/components/StepperHorizontal";
|
||||
import { TextInput } from "~/ui/components/TextInput";
|
||||
import Captcha from "~/components/captcha/Captcha";
|
||||
import { getPasswordChecks, type PasswordPolicy } from "~/modules/users/components/RegisterForm";
|
||||
import { RegistrationPlanStep } from "~/modules/users/components/RegistrationPlanStep";
|
||||
|
||||
// Signup-Screens nach Davids Subframe-"WF-P2"-Designs:
|
||||
// S01 "Signup" -> Form (Logo + Card "Konto erstellen": E-Mail, Passwort+Staerke, Vor-/Nachname,
|
||||
@@ -26,32 +26,74 @@ import { getPasswordChecks, type PasswordPolicy } from "~/modules/users/componen
|
||||
// Token-genaue Uebernahme + bewusste Abweichungen (vom Backend erzwungen, nicht erfunden):
|
||||
// - Davids S01 zeigt das Passwort IMMER. Bei aktiver E-Mail-Verifizierung sammelt das Backend das Passwort
|
||||
// aber erst beim Verify (Registration-Modell hat KEINE Passwort-Spalte) -> showPasswordInput bleibt
|
||||
// `!requireEmailVerification` (Default ist OFF -> Passwort sichtbar = Davids Optik). [Backend-Flag]
|
||||
// `!requireEmailVerification` (launch-sicherer Default ist ON -> Passwort genau einmal im Verify-Schritt).
|
||||
// Eine explizit deaktivierte Verifizierung zeigt das Passwort weiterhin direkt in S01. [Backend-Flag]
|
||||
// - Davids S01 hat KEIN Telefon-/USt-IdNr-Feld -> entfernt (wurden ohnehin nie persistiert).
|
||||
// - Davids S01 hat 2 Consents (AGB, Datenschutz); der separate AVV/DPA-Consent wurde gestrichen. [Flag]
|
||||
// - Davids PasswordStrengthIndicator existiert nicht in ~/ui -> bestehender Progress-Balken beibehalten.
|
||||
// - Davids statische Captcha-Box ("Ich bin kein Roboter") -> echtes mCaptcha-Widget in Davids Box-Optik,
|
||||
// nur sichtbar wenn Captcha aktiv ist.
|
||||
// - S03 "E-Mail erneut senden": echtes Resend braucht `recreateToken:true` (registerFromRequest nutzt
|
||||
// `false` -> versendet bei bestehender Registration NICHTS). Button postet `intent=resendVerification`;
|
||||
// das Backend muss diesen Intent noch auf createRegistrationForm({recreateToken:true}) mappen. [Backend-Flag]
|
||||
// - S03 resend posts `intent=resendVerification`. The server verifies the persisted HMAC-bound pending
|
||||
// capability, rotates its token and TTL atomically, and returns the new request key for the next click.
|
||||
|
||||
type RegisterData = { company?: string; firstName?: string; lastName?: string; email?: string; slug?: string };
|
||||
|
||||
export type RegistrationPlanOptionData = {
|
||||
readonly planId: string;
|
||||
readonly planCode: string;
|
||||
readonly titleKey: string;
|
||||
readonly descriptionKey: string;
|
||||
readonly priceId: string;
|
||||
readonly amountCents: number;
|
||||
readonly baseAmountCents: number;
|
||||
readonly currency: string;
|
||||
readonly billingPeriod: number;
|
||||
readonly includedOfficeSeatQuantity: number;
|
||||
readonly includedFieldSeatQuantity: number;
|
||||
readonly includedStorageGb: number;
|
||||
readonly storagePerAdditionalSeatGb: number;
|
||||
readonly extraOfficeSeatQuantity: number;
|
||||
readonly extraFieldSeatQuantity: number;
|
||||
readonly recommended: boolean;
|
||||
};
|
||||
|
||||
type RegistrationPlanAdviceData = {
|
||||
readonly plans: readonly RegistrationPlanOptionData[];
|
||||
readonly selectedPriceId: string;
|
||||
readonly recommendedPriceId: string;
|
||||
readonly officeSeatQuantity: number;
|
||||
readonly fieldSeatQuantity: number;
|
||||
};
|
||||
|
||||
export default function RegisterScreen({
|
||||
requireCaptcha = false,
|
||||
error,
|
||||
captchaResetKey,
|
||||
verificationEmailSent,
|
||||
data = {},
|
||||
leadConversion,
|
||||
passwordPolicy,
|
||||
creationRequestKey,
|
||||
subscriptionPlans,
|
||||
selectedSubscriptionPriceId,
|
||||
recommendedSubscriptionPriceId,
|
||||
initialOfficeSeatQuantity,
|
||||
initialFieldSeatQuantity,
|
||||
}: {
|
||||
requireCaptcha?: boolean;
|
||||
error?: string;
|
||||
/** Changes after every failed initial submit so single-use CAPTCHA proofs cannot poison retries. */
|
||||
captchaResetKey?: string;
|
||||
verificationEmailSent?: boolean;
|
||||
data?: RegisterData;
|
||||
leadConversion?: { leadId: string; token: string; planId?: string | null };
|
||||
passwordPolicy?: PasswordPolicy;
|
||||
creationRequestKey: string;
|
||||
subscriptionPlans: readonly RegistrationPlanOptionData[];
|
||||
selectedSubscriptionPriceId: string;
|
||||
recommendedSubscriptionPriceId: string;
|
||||
initialOfficeSeatQuantity: number;
|
||||
initialFieldSeatQuantity: number;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { appConfiguration, csrf } = useRootData();
|
||||
@@ -60,6 +102,8 @@ export default function RegisterScreen({
|
||||
const [searchParams] = useSearchParams();
|
||||
const isSubmitting = navigation.state !== "idle";
|
||||
const redirect = searchParams.get("redirect") ?? "";
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
const passwordInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// Controlled, damit Werte ueber den Wechsel Form <-> "E-Mail bestaetigt"-Status erhalten bleiben
|
||||
// (E-Mail-Anzeige in S03, Resend ohne erneutes Tippen).
|
||||
@@ -68,21 +112,96 @@ export default function RegisterScreen({
|
||||
const [company, setCompany] = useState(data.company ?? "");
|
||||
const [firstName, setFirstName] = useState(data.firstName ?? "");
|
||||
const [lastName, setLastName] = useState(data.lastName ?? "");
|
||||
const [selectedPriceId, setSelectedPriceId] = useState(selectedSubscriptionPriceId);
|
||||
const [step, setStep] = useState<"account" | "team" | "plan">("account");
|
||||
const [officeSeatQuantity, setOfficeSeatQuantity] = useState(initialOfficeSeatQuantity);
|
||||
const [fieldSeatQuantity, setFieldSeatQuantity] = useState(initialFieldSeatQuantity);
|
||||
const [planOptions, setPlanOptions] = useState(subscriptionPlans);
|
||||
const [recommendedPriceId, setRecommendedPriceId] = useState(recommendedSubscriptionPriceId);
|
||||
const [planManuallyOverridden, setPlanManuallyOverridden] = useState(selectedSubscriptionPriceId !== recommendedSubscriptionPriceId);
|
||||
const [planAdviceLoading, setPlanAdviceLoading] = useState(false);
|
||||
const [planAdviceFailed, setPlanAdviceFailed] = useState(false);
|
||||
const [planAdviceRetryKey, setPlanAdviceRetryKey] = useState(0);
|
||||
const [acceptTerms, setAcceptTerms] = useState(false);
|
||||
const [acceptPrivacy, setAcceptPrivacy] = useState(false);
|
||||
const allConsents = acceptTerms && acceptPrivacy;
|
||||
const [captchaStatus, setCaptchaStatus] = useState<"pending" | "solved" | "error">("pending");
|
||||
const [passwordValidationRequested, setPasswordValidationRequested] = useState(false);
|
||||
|
||||
const requireEmailVerification = appConfiguration.auth.requireEmailVerification;
|
||||
const showPasswordInput = !requireEmailVerification;
|
||||
const captchaEnabled = requireCaptcha && appConfiguration.auth.captcha.enabled;
|
||||
const checks = useMemo(() => getPasswordChecks(password, passwordPolicy), [password, passwordPolicy]);
|
||||
const strength = checks.length === 0 ? 0 : Math.round((checks.filter((c) => c.valid).length / checks.length) * 100);
|
||||
const passwordMeetsClientPolicy = !showPasswordInput || checks.length === 0 || checks.every((check) => check.valid);
|
||||
const showPasswordPolicyError = passwordValidationRequested && !passwordMeetsClientPolicy;
|
||||
|
||||
useEffect(() => {
|
||||
if (captchaResetKey) setCaptchaStatus("pending");
|
||||
}, [captchaResetKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (verificationEmailSent) return;
|
||||
if (
|
||||
!Number.isSafeInteger(officeSeatQuantity) ||
|
||||
!Number.isSafeInteger(fieldSeatQuantity) ||
|
||||
officeSeatQuantity < 1 ||
|
||||
officeSeatQuantity > 10_000 ||
|
||||
fieldSeatQuantity < 0 ||
|
||||
fieldSeatQuantity > 10_000
|
||||
) {
|
||||
setPlanAdviceFailed(true);
|
||||
return;
|
||||
}
|
||||
const controller = new AbortController();
|
||||
const timer = window.setTimeout(async () => {
|
||||
setPlanAdviceLoading(true);
|
||||
setPlanAdviceFailed(false);
|
||||
try {
|
||||
const params = new URLSearchParams({ office: String(officeSeatQuantity), field: String(fieldSeatQuantity) });
|
||||
const response = await fetch(`/auth/registration-plan-advice?${params}`, {
|
||||
headers: { Accept: "application/json" },
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!response.ok) throw new Error("Registration plan advice failed");
|
||||
const advice = (await response.json()) as RegistrationPlanAdviceData;
|
||||
setPlanOptions(advice.plans);
|
||||
setRecommendedPriceId(advice.recommendedPriceId);
|
||||
if (!planManuallyOverridden) setSelectedPriceId(advice.recommendedPriceId);
|
||||
} catch {
|
||||
if (!controller.signal.aborted) setPlanAdviceFailed(true);
|
||||
} finally {
|
||||
if (!controller.signal.aborted) setPlanAdviceLoading(false);
|
||||
}
|
||||
}, 250);
|
||||
return () => {
|
||||
window.clearTimeout(timer);
|
||||
controller.abort();
|
||||
};
|
||||
}, [fieldSeatQuantity, officeSeatQuantity, planAdviceRetryKey, planManuallyOverridden, verificationEmailSent]);
|
||||
|
||||
function showTeamStep() {
|
||||
setPasswordValidationRequested(true);
|
||||
const accountStep = formRef.current?.querySelector('[data-ui-id="ui.auth.register.accountStep"]');
|
||||
if (!accountStep) return;
|
||||
const controls = Array.from(accountStep.querySelectorAll<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>("input, select, textarea"));
|
||||
const nativeFieldsValid = controls.every((control) => control.reportValidity());
|
||||
if (!passwordMeetsClientPolicy) {
|
||||
passwordInputRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
if (nativeFieldsValid) setStep("team");
|
||||
}
|
||||
|
||||
function selectPlan(priceId: string) {
|
||||
setPlanManuallyOverridden(true);
|
||||
setSelectedPriceId(priceId);
|
||||
}
|
||||
|
||||
// S03 "E-Mail bestaetigen" — Davids Status-Card.
|
||||
if (verificationEmailSent) {
|
||||
return (
|
||||
<div
|
||||
className="flex min-h-screen w-full flex-col items-center justify-center gap-8 bg-surface-neutral-primary px-4 py-12 mobile:gap-6 mobile:py-6"
|
||||
className="bg-surface-neutral-primary mobile:gap-6 mobile:py-6 flex min-h-screen w-full flex-col items-center justify-center gap-8 px-4 py-12"
|
||||
data-ui-id="ui.auth.register.verificationSent"
|
||||
>
|
||||
<Logo size="64" />
|
||||
@@ -91,28 +210,46 @@ export default function RegisterScreen({
|
||||
<IconWithBackground variant="information" size="large" round={true} icon={<FeatherMailCheck />} />
|
||||
<div className="flex w-full flex-col items-center gap-2">
|
||||
<span className="text-heading- font-heading- text-text-neutral-primary text-center">{t("account.verify.confirmEmailTitle")}</span>
|
||||
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary text-center">
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary w-full text-center">
|
||||
{t("account.verify.confirmEmailBody")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex w-full flex-col items-center gap-2 rounded-md border border-solid border-border-default bg-surface-neutral-primary px-4 py-3">
|
||||
<span className="text-body-extra-small-medium-150 font-body-extra-small-medium-150 text-text-neutral-tertiary">{t("account.verify.linkSentTo")}</span>
|
||||
<span className="w-full text-body-default-semibold-0 font-body-default-semibold-0 text-text-neutral-primary text-center" data-ui-id="ui.auth.register.sentEmail">
|
||||
<div className="border-border-default bg-surface-neutral-primary flex w-full flex-col items-center gap-2 rounded-md border border-solid px-4 py-3">
|
||||
<span className="text-body-extra-small-medium-150 font-body-extra-small-medium-150 text-text-neutral-tertiary">
|
||||
{t("account.verify.linkSentTo")}
|
||||
</span>
|
||||
<span
|
||||
className="text-body-default-semibold-0 font-body-default-semibold-0 text-text-neutral-primary w-full text-center"
|
||||
data-ui-id="ui.auth.register.sentEmail"
|
||||
>
|
||||
{email}
|
||||
</span>
|
||||
</div>
|
||||
<Alert variant="neutral" notDismissible={true} title="" description={t("account.verify.checkInboxHint")} />
|
||||
{error && navigation.state === "idle" ? (
|
||||
<p
|
||||
className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative text-center"
|
||||
role="alert"
|
||||
data-ui-id="ui.auth.register.resendError"
|
||||
>
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="flex w-full flex-col items-center gap-3">
|
||||
{/* Resend: echtes Re-Send ist backend-seitig offen (recreateToken:true) -> Intent posten + Flag. */}
|
||||
{/* The resend intent proves the persisted HMAC-bound pending capability; the server rotates token and TTL before queueing a new mail job. */}
|
||||
<Form method="post" className="w-full">
|
||||
<input type="hidden" name="csrf" value={csrf} readOnly />
|
||||
<input type="hidden" name="redirectTo" value={redirect} readOnly />
|
||||
<input type="hidden" name="intent" value="resendVerification" readOnly />
|
||||
<input type="hidden" name="creationRequestKey" value={creationRequestKey} readOnly />
|
||||
<input type="hidden" name="email" value={email} readOnly />
|
||||
<input type="hidden" name="company" value={company} readOnly />
|
||||
<input type="hidden" name="first-name" value={firstName} readOnly />
|
||||
<input type="hidden" name="last-name" value={lastName} readOnly />
|
||||
<input type="hidden" name="selectedSubscriptionPriceId" value={selectedPriceId} readOnly />
|
||||
<input type="hidden" name="selectedOfficeSeatQuantity" value={officeSeatQuantity} readOnly />
|
||||
<input type="hidden" name="selectedFieldSeatQuantity" value={fieldSeatQuantity} readOnly />
|
||||
{leadConversion ? (
|
||||
<>
|
||||
<input type="hidden" name="leadId" value={leadConversion.leadId} readOnly />
|
||||
@@ -135,7 +272,7 @@ export default function RegisterScreen({
|
||||
className="h-10 w-full flex-none"
|
||||
variant="secondary"
|
||||
icon={<FeatherPencil />}
|
||||
onClick={() => navigate("/signup")}
|
||||
onClick={() => navigate("/signup?restart=1")}
|
||||
data-ui-id="ui.auth.register.changeEmail"
|
||||
>
|
||||
{t("account.verify.changeEmail")}
|
||||
@@ -149,7 +286,7 @@ export default function RegisterScreen({
|
||||
</Link>
|
||||
</div>
|
||||
</Card>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary text-center max-w-[400px]">
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary max-w-[400px] text-center">
|
||||
{t("account.verify.linkValidityNote")}
|
||||
</span>
|
||||
</div>
|
||||
@@ -159,8 +296,17 @@ export default function RegisterScreen({
|
||||
// S01 "Signup".
|
||||
return (
|
||||
<AuthShell
|
||||
title={t("account.register.title")}
|
||||
subtitle={t("account.register.signupSubtitle")}
|
||||
title={step === "account" ? t("account.register.title") : step === "team" ? t("account.register.teamStepTitle") : t("account.register.planStepTitle")}
|
||||
subtitle={
|
||||
step === "account"
|
||||
? t("account.register.signupSubtitle")
|
||||
: step === "team"
|
||||
? t("account.register.teamStepSubtitle")
|
||||
: t("account.register.planStepSubtitle")
|
||||
}
|
||||
cardSize={step === "account" ? "large" : "extra-large"}
|
||||
cardClassName={step === "account" ? "max-w-[448px]" : "max-w-[960px]"}
|
||||
logoSize="32"
|
||||
dataUiId="ui.auth.register.page"
|
||||
footer={
|
||||
<>
|
||||
@@ -174,9 +320,27 @@ export default function RegisterScreen({
|
||||
}
|
||||
>
|
||||
{appConfiguration.auth.authMethods.emailPassword.enabled ? (
|
||||
<Form method="post" noValidate className="flex w-full flex-col gap-4" data-ui-id="ui.auth.register.form">
|
||||
<Form ref={formRef} method="post" className="flex w-full flex-col gap-4" data-ui-id="ui.auth.register.form">
|
||||
<StepperHorizontal className="pb-1" data-ui-id="ui.auth.register.steps">
|
||||
<StepperHorizontal.Step
|
||||
firstStep
|
||||
variant={step === "account" ? "active" : "completed"}
|
||||
stepNumber="1"
|
||||
label={t("account.register.accountStepLabel")}
|
||||
/>
|
||||
<StepperHorizontal.Step
|
||||
variant={step === "team" ? "active" : step === "plan" ? "completed" : "default"}
|
||||
stepNumber="2"
|
||||
label={t("account.register.teamStepLabel")}
|
||||
/>
|
||||
<StepperHorizontal.Step lastStep variant={step === "plan" ? "active" : "default"} stepNumber="3" label={t("account.register.planStepLabel")} />
|
||||
</StepperHorizontal>
|
||||
<input type="hidden" name="redirectTo" value={redirect} readOnly />
|
||||
<input type="hidden" name="csrf" value={csrf} readOnly />
|
||||
<input type="hidden" name="creationRequestKey" value={creationRequestKey} readOnly />
|
||||
<input type="hidden" name="selectedSubscriptionPriceId" value={selectedPriceId} readOnly />
|
||||
<input type="hidden" name="acceptTerms" value={acceptTerms ? "true" : "false"} readOnly />
|
||||
<input type="hidden" name="acceptPrivacy" value={acceptPrivacy ? "true" : "false"} readOnly />
|
||||
{leadConversion ? (
|
||||
<>
|
||||
<input type="hidden" name="leadId" value={leadConversion.leadId} readOnly />
|
||||
@@ -185,151 +349,180 @@ export default function RegisterScreen({
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{/* Davids Felder-Gruppe (gap-4). */}
|
||||
<div className="flex w-full flex-col items-start gap-4">
|
||||
<TextInput className="h-auto w-full flex-none" fillContainer showLabel label={t("account.shared.email")} type="email">
|
||||
<TextInput.Input
|
||||
name="email"
|
||||
type="email"
|
||||
required
|
||||
autoComplete="email"
|
||||
placeholder={t("account.shared.emailPlaceholder")}
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
readOnly={Boolean(leadConversion)}
|
||||
disabled={isSubmitting}
|
||||
data-ui-id="ui.auth.register.email"
|
||||
/>
|
||||
</TextInput>
|
||||
<div className={step === "account" ? "flex w-full flex-col gap-4" : "hidden"} data-ui-id="ui.auth.register.accountStep">
|
||||
{/* Davids Felder-Gruppe (gap-4). */}
|
||||
<div className="flex w-full flex-col items-start gap-4">
|
||||
<TextInput className="h-auto w-full flex-none" fillContainer showLabel label={t("account.shared.email")} type="email">
|
||||
<TextInput.Input
|
||||
name="email"
|
||||
type="email"
|
||||
required
|
||||
autoComplete="email"
|
||||
placeholder={t("account.shared.emailPlaceholder")}
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
readOnly={Boolean(leadConversion)}
|
||||
disabled={isSubmitting}
|
||||
data-ui-id="ui.auth.register.email"
|
||||
/>
|
||||
</TextInput>
|
||||
|
||||
{showPasswordInput ? (
|
||||
<div className="flex w-full flex-col items-start gap-2">
|
||||
<TextInput className="h-auto w-full flex-none" fillContainer showLabel label={t("account.shared.password")} type="password">
|
||||
<TextInput.Input
|
||||
name="password"
|
||||
{showPasswordInput ? (
|
||||
<div className="flex w-full flex-col items-start gap-2">
|
||||
<TextInput
|
||||
className="h-auto w-full flex-none"
|
||||
fillContainer
|
||||
showLabel
|
||||
label={t("account.shared.password")}
|
||||
type="password"
|
||||
required
|
||||
autoComplete="new-password"
|
||||
placeholder={t("account.register.passwordChoosePlaceholder")}
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
error={showPasswordPolicyError}
|
||||
message={
|
||||
showPasswordPolicyError ? (
|
||||
<span id="registration-password-policy-error" role="alert" data-ui-id="ui.auth.register.passwordPolicyError">
|
||||
{t("account.register.passwordRequirements.fixBeforeContinue")}
|
||||
</span>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<TextInput.Input
|
||||
ref={passwordInputRef}
|
||||
name="password"
|
||||
type="password"
|
||||
required
|
||||
autoComplete="new-password"
|
||||
placeholder={t("account.register.passwordChoosePlaceholder")}
|
||||
value={password}
|
||||
onChange={(event) => {
|
||||
setPassword(event.target.value);
|
||||
if (passwordValidationRequested) setPasswordValidationRequested(false);
|
||||
}}
|
||||
onBlur={() => {
|
||||
if (password.length > 0 && !passwordMeetsClientPolicy) setPasswordValidationRequested(true);
|
||||
}}
|
||||
aria-invalid={showPasswordPolicyError}
|
||||
aria-describedby={showPasswordPolicyError ? "registration-password-policy-error" : undefined}
|
||||
disabled={isSubmitting}
|
||||
data-ui-id="ui.auth.register.password"
|
||||
/>
|
||||
</TextInput>
|
||||
{passwordPolicy ? (
|
||||
<>
|
||||
<Progress className="h-auto w-full flex-none" hideLabel label={t("account.register.passwordStrength")} value={strength} />
|
||||
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-tertiary">
|
||||
{t("account.register.passwordStrength")}
|
||||
</span>
|
||||
<ul
|
||||
className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 flex w-full flex-col gap-1"
|
||||
aria-live="polite"
|
||||
aria-label={t("account.register.passwordRequirements.label")}
|
||||
data-ui-id="ui.auth.register.passwordRequirements"
|
||||
>
|
||||
{checks.map((check) => {
|
||||
const label = t(check.label, check.args);
|
||||
const status = check.valid ? t("account.register.passwordRequirements.met") : t("account.register.passwordRequirements.notMet");
|
||||
return (
|
||||
<li
|
||||
key={check.key}
|
||||
className={
|
||||
check.valid
|
||||
? "text-text-feedback-positive"
|
||||
: showPasswordPolicyError
|
||||
? "text-text-feedback-negative"
|
||||
: "text-text-neutral-tertiary"
|
||||
}
|
||||
aria-label={`${status}: ${label}`}
|
||||
>
|
||||
<span aria-hidden="true">{check.valid ? "[x]" : "[ ]"}</span> {label}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="mobile:flex-col flex w-full items-start gap-4">
|
||||
<TextInput className="h-auto shrink-0 grow basis-0" showLabel label={t("models.user.firstName")}>
|
||||
<TextInput.Input
|
||||
name="first-name"
|
||||
required={appConfiguration.auth.requireName}
|
||||
placeholder={t("account.shared.firstNamePlaceholder")}
|
||||
value={firstName}
|
||||
onChange={(event) => setFirstName(event.target.value)}
|
||||
disabled={isSubmitting}
|
||||
data-ui-id="ui.auth.register.password"
|
||||
data-ui-id="ui.auth.register.firstName"
|
||||
/>
|
||||
</TextInput>
|
||||
<TextInput className="h-auto shrink-0 grow basis-0" showLabel label={t("models.user.lastName")}>
|
||||
<TextInput.Input
|
||||
name="last-name"
|
||||
required={appConfiguration.auth.requireName}
|
||||
placeholder={t("account.shared.lastNamePlaceholder")}
|
||||
value={lastName}
|
||||
onChange={(event) => setLastName(event.target.value)}
|
||||
disabled={isSubmitting}
|
||||
data-ui-id="ui.auth.register.lastName"
|
||||
/>
|
||||
</TextInput>
|
||||
{passwordPolicy ? (
|
||||
<>
|
||||
<Progress className="h-auto w-full flex-none" hideLabel value={strength} />
|
||||
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-tertiary">{t("account.register.passwordStrength")}</span>
|
||||
<span className="w-full text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">{t("account.register.passwordHint")}</span>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="flex w-full items-start gap-4 mobile:flex-col">
|
||||
<TextInput className="h-auto grow shrink-0 basis-0" showLabel label={t("models.user.firstName")}>
|
||||
<TextInput className="h-auto w-full flex-none" fillContainer showLabel label={t("account.register.companyLabel")} icon={<FeatherBuilding />}>
|
||||
<TextInput.Input
|
||||
name="first-name"
|
||||
placeholder={t("account.shared.firstNamePlaceholder")}
|
||||
value={firstName}
|
||||
onChange={(event) => setFirstName(event.target.value)}
|
||||
name="company"
|
||||
required={appConfiguration.auth.requireOrganization}
|
||||
placeholder={t("account.register.companyPlaceholder")}
|
||||
value={company}
|
||||
onChange={(event) => setCompany(event.target.value)}
|
||||
disabled={isSubmitting}
|
||||
data-ui-id="ui.auth.register.firstName"
|
||||
/>
|
||||
</TextInput>
|
||||
<TextInput className="h-auto grow shrink-0 basis-0" showLabel label={t("models.user.lastName")}>
|
||||
<TextInput.Input
|
||||
name="last-name"
|
||||
placeholder={t("account.shared.lastNamePlaceholder")}
|
||||
value={lastName}
|
||||
onChange={(event) => setLastName(event.target.value)}
|
||||
disabled={isSubmitting}
|
||||
data-ui-id="ui.auth.register.lastName"
|
||||
data-ui-id="ui.auth.register.company"
|
||||
/>
|
||||
</TextInput>
|
||||
</div>
|
||||
|
||||
<TextInput
|
||||
className="h-auto w-full flex-none"
|
||||
fillContainer
|
||||
showLabel
|
||||
label={t("account.register.companyLabel")}
|
||||
icon={<FeatherBuilding />}
|
||||
>
|
||||
<TextInput.Input
|
||||
name="company"
|
||||
required={appConfiguration.auth.requireOrganization}
|
||||
placeholder={t("account.register.companyPlaceholder")}
|
||||
value={company}
|
||||
onChange={(event) => setCompany(event.target.value)}
|
||||
disabled={isSubmitting}
|
||||
data-ui-id="ui.auth.register.company"
|
||||
/>
|
||||
</TextInput>
|
||||
</div>
|
||||
|
||||
{/* Sicherheitspruefung — Davids Box mit echtem mCaptcha-Widget statt statischer Mock-Checkbox. */}
|
||||
{captchaEnabled ? (
|
||||
<div className="flex w-full flex-col items-start gap-2">
|
||||
<span className="text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 uppercase text-text-neutral-tertiary">
|
||||
{t("account.register.securityCheck")}
|
||||
</span>
|
||||
<div className="flex w-full items-center justify-center rounded-md border border-solid border-border-default bg-surface-neutral-secondary px-4 py-3">
|
||||
<Captcha
|
||||
enabled
|
||||
provider={appConfiguration.auth.captcha.provider}
|
||||
instanceUrl={appConfiguration.auth.captcha.instanceUrl}
|
||||
sitekey={appConfiguration.auth.captcha.loginSiteKey}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Consents — Davids 2 Checkboxen mit Prefix + Link. */}
|
||||
<div className="flex w-full flex-col items-start gap-3">
|
||||
<div className="flex w-full items-center gap-2">
|
||||
<Checkbox label={t("account.register.consentTerms")} hideLabel checked={acceptTerms} onCheckedChange={setAcceptTerms} data-ui-id="ui.auth.register.consentTerms" />
|
||||
<div className="flex min-h-5 flex-wrap items-center gap-1">
|
||||
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">{t("account.register.consentAcceptPrefix")}</span>
|
||||
<a href="/terms-and-conditions" target="_blank" rel="noreferrer" className="no-underline">
|
||||
<LinkButton size="small" hideIcon>
|
||||
{t("account.register.consentTermsLink")}
|
||||
</LinkButton>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex w-full items-center gap-2">
|
||||
<Checkbox label={t("account.register.consentPrivacy")} hideLabel checked={acceptPrivacy} onCheckedChange={setAcceptPrivacy} data-ui-id="ui.auth.register.consentPrivacy" />
|
||||
<div className="flex min-h-5 flex-wrap items-center gap-1">
|
||||
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">{t("account.register.consentAcceptPrefix")}</span>
|
||||
<a href="/privacy-policy" target="_blank" rel="noreferrer" className="no-underline">
|
||||
<LinkButton size="small" hideIcon>
|
||||
{t("account.register.privacyPolicy")}
|
||||
</LinkButton>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Button-Gruppe — Submit + Bestaetigungs-Mail-Hinweis (nur wenn verifiziert wird). */}
|
||||
<div className="flex w-full flex-col items-start gap-2">
|
||||
<Button type="submit" className="h-9 w-full flex-none" loading={isSubmitting} disabled={isSubmitting || !allConsents} data-ui-id="ui.auth.register.submit">
|
||||
{t("account.register.title")}
|
||||
<Button type="button" className="h-9 w-full flex-none" onClick={showTeamStep} data-ui-id="ui.auth.register.toTeamStep">
|
||||
{t("account.register.continueToTeam")}
|
||||
</Button>
|
||||
{requireEmailVerification ? (
|
||||
<div className="flex w-full items-center justify-center gap-1">
|
||||
<FeatherMail className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
|
||||
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">{t("account.register.confirmationEmailNote")}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{error && navigation.state === "idle" ? (
|
||||
<p className="text-center text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
<RegistrationPlanStep
|
||||
visible={step !== "account"}
|
||||
screen={step === "team" ? "team" : "plan"}
|
||||
plans={planOptions}
|
||||
selectedPriceId={selectedPriceId}
|
||||
recommendedPriceId={recommendedPriceId}
|
||||
officeSeatQuantity={officeSeatQuantity}
|
||||
fieldSeatQuantity={fieldSeatQuantity}
|
||||
planAdviceLoading={planAdviceLoading}
|
||||
planAdviceFailed={planAdviceFailed}
|
||||
isSubmitting={isSubmitting}
|
||||
acceptTerms={acceptTerms}
|
||||
acceptPrivacy={acceptPrivacy}
|
||||
captchaEnabled={captchaEnabled}
|
||||
captchaConfig={appConfiguration.auth.captcha}
|
||||
captchaResetKey={captchaResetKey}
|
||||
captchaStatus={captchaStatus}
|
||||
requireEmailVerification={requireEmailVerification}
|
||||
error={navigation.state === "idle" ? error : undefined}
|
||||
onSelectPlan={selectPlan}
|
||||
onOfficeSeatQuantityChange={setOfficeSeatQuantity}
|
||||
onFieldSeatQuantityChange={setFieldSeatQuantity}
|
||||
onAcceptTermsChange={setAcceptTerms}
|
||||
onAcceptPrivacyChange={setAcceptPrivacy}
|
||||
onCaptchaStatusChange={setCaptchaStatus}
|
||||
onRetryPlanAdvice={() => {
|
||||
setPlanAdviceFailed(false);
|
||||
setPlanAdviceRetryKey((current) => current + 1);
|
||||
}}
|
||||
onContinue={() => setStep("plan")}
|
||||
onBack={() => setStep(step === "plan" ? "team" : "account")}
|
||||
/>
|
||||
{/* The interactive seat controls live only on the team step and are
|
||||
unmounted on the final plan step. Keep the submitted contract
|
||||
present for the whole wizard so server-side price validation
|
||||
always receives the exact quantities the customer reviewed. */}
|
||||
<input type="hidden" name="selectedOfficeSeatQuantity" value={officeSeatQuantity} readOnly />
|
||||
<input type="hidden" name="selectedFieldSeatQuantity" value={fieldSeatQuantity} readOnly />
|
||||
</Form>
|
||||
) : null}
|
||||
</AuthShell>
|
||||
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
import { useMemo } from "react";
|
||||
import { createMemoryRouter, RouterProvider } from "react-router";
|
||||
|
||||
import RegisterScreen, { type RegistrationPlanOptionData } from "./RegisterScreen";
|
||||
|
||||
const plans: readonly RegistrationPlanOptionData[] = [
|
||||
{
|
||||
planId: "product_starter",
|
||||
planCode: "starter",
|
||||
titleKey: "pricing.products.plan1.title",
|
||||
descriptionKey: "pricing.products.plan1.description",
|
||||
priceId: "price_starter",
|
||||
amountCents: 19_900,
|
||||
baseAmountCents: 19_900,
|
||||
currency: "EUR",
|
||||
billingPeriod: 3,
|
||||
includedOfficeSeatQuantity: 2,
|
||||
includedFieldSeatQuantity: 5,
|
||||
includedStorageGb: 100,
|
||||
storagePerAdditionalSeatGb: 10,
|
||||
extraOfficeSeatQuantity: 0,
|
||||
extraFieldSeatQuantity: 0,
|
||||
recommended: true,
|
||||
},
|
||||
{
|
||||
planId: "product_pro",
|
||||
planCode: "pro",
|
||||
titleKey: "pricing.products.plan2.title",
|
||||
descriptionKey: "pricing.products.plan2.description",
|
||||
priceId: "price_pro",
|
||||
amountCents: 49_900,
|
||||
baseAmountCents: 49_900,
|
||||
currency: "EUR",
|
||||
billingPeriod: 3,
|
||||
includedOfficeSeatQuantity: 5,
|
||||
includedFieldSeatQuantity: 15,
|
||||
includedStorageGb: 500,
|
||||
storagePerAdditionalSeatGb: 20,
|
||||
extraOfficeSeatQuantity: 0,
|
||||
extraFieldSeatQuantity: 0,
|
||||
recommended: false,
|
||||
},
|
||||
{
|
||||
planId: "product_business",
|
||||
planCode: "business",
|
||||
titleKey: "pricing.products.plan3.title",
|
||||
descriptionKey: "pricing.products.plan3.description",
|
||||
priceId: "price_business",
|
||||
amountCents: 99_900,
|
||||
baseAmountCents: 99_900,
|
||||
currency: "EUR",
|
||||
billingPeriod: 3,
|
||||
includedOfficeSeatQuantity: 10,
|
||||
includedFieldSeatQuantity: 30,
|
||||
includedStorageGb: 2_000,
|
||||
storagePerAdditionalSeatGb: 40,
|
||||
extraOfficeSeatQuantity: 0,
|
||||
extraFieldSeatQuantity: 0,
|
||||
recommended: false,
|
||||
},
|
||||
];
|
||||
|
||||
const rootData = {
|
||||
csrf: "visual-csrf",
|
||||
appConfiguration: {
|
||||
auth: {
|
||||
requireEmailVerification: true,
|
||||
requireOrganization: true,
|
||||
requireName: true,
|
||||
authMethods: { emailPassword: { enabled: true } },
|
||||
captcha: {
|
||||
enabled: true,
|
||||
provider: "cap" as const,
|
||||
instanceUrl: "https://captcha.visual.invalid",
|
||||
loginSiteKey: "registration-visual",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/** Real registration component in a deterministic data-router shell for visual regression. */
|
||||
export function RegisterScreenVisualFixture({ requireEmailVerification = true }: { requireEmailVerification?: boolean } = {}) {
|
||||
const router = useMemo(
|
||||
() =>
|
||||
createMemoryRouter(
|
||||
[
|
||||
{
|
||||
id: "root",
|
||||
path: "/",
|
||||
loader: () => ({
|
||||
...rootData,
|
||||
appConfiguration: {
|
||||
...rootData.appConfiguration,
|
||||
auth: { ...rootData.appConfiguration.auth, requireEmailVerification },
|
||||
},
|
||||
}),
|
||||
element: (
|
||||
<RegisterScreen
|
||||
requireCaptcha
|
||||
creationRequestKey="d7077797-054b-497a-b1ce-8e4f36257a96"
|
||||
subscriptionPlans={plans}
|
||||
selectedSubscriptionPriceId="price_starter"
|
||||
recommendedSubscriptionPriceId="price_starter"
|
||||
initialOfficeSeatQuantity={1}
|
||||
initialFieldSeatQuantity={0}
|
||||
passwordPolicy={{ minLength: 12, requireUpper: true, requireLower: true, requireDigit: true, requireSpecial: true }}
|
||||
/>
|
||||
),
|
||||
},
|
||||
],
|
||||
{ initialEntries: ["/"] }
|
||||
),
|
||||
[requireEmailVerification]
|
||||
);
|
||||
|
||||
return <RouterProvider router={router} />;
|
||||
}
|
||||
+486
@@ -0,0 +1,486 @@
|
||||
import {
|
||||
FeatherArrowLeft,
|
||||
FeatherBriefcase,
|
||||
FeatherCheck,
|
||||
FeatherCreditCard,
|
||||
FeatherHardHat,
|
||||
FeatherLock,
|
||||
FeatherMail,
|
||||
FeatherMinus,
|
||||
FeatherPlus,
|
||||
FeatherUsers,
|
||||
} from "@subframe/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import Captcha from "~/components/captcha/Captcha";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { Alert } from "~/ui/components/Alert";
|
||||
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
|
||||
import { Button } from "~/ui/components/Button";
|
||||
import { Card } from "~/ui/components/Card";
|
||||
import { Checkbox } from "~/ui/components/Checkbox";
|
||||
import { IconButton } from "~/ui/components/IconButton";
|
||||
import { IconWithBackground } from "~/ui/components/IconWithBackground";
|
||||
import { LinkButton } from "~/ui/components/LinkButton";
|
||||
import { RadioCardGroup } from "~/ui/components/RadioCardGroup";
|
||||
import { Slider } from "~/ui/components/Slider";
|
||||
import { TextInput } from "~/ui/components/TextInput";
|
||||
|
||||
import type { RegistrationPlanOptionData } from "./RegisterScreen";
|
||||
|
||||
type CaptchaStatus = "pending" | "solved" | "error";
|
||||
|
||||
export function RegistrationPlanStep({
|
||||
visible,
|
||||
screen,
|
||||
plans,
|
||||
selectedPriceId,
|
||||
recommendedPriceId,
|
||||
officeSeatQuantity,
|
||||
fieldSeatQuantity,
|
||||
planAdviceLoading,
|
||||
planAdviceFailed,
|
||||
isSubmitting,
|
||||
acceptTerms,
|
||||
acceptPrivacy,
|
||||
captchaEnabled,
|
||||
captchaConfig,
|
||||
captchaResetKey,
|
||||
captchaStatus,
|
||||
requireEmailVerification,
|
||||
error,
|
||||
onSelectPlan,
|
||||
onOfficeSeatQuantityChange,
|
||||
onFieldSeatQuantityChange,
|
||||
onAcceptTermsChange,
|
||||
onAcceptPrivacyChange,
|
||||
onCaptchaStatusChange,
|
||||
onRetryPlanAdvice,
|
||||
onContinue,
|
||||
onBack,
|
||||
}: {
|
||||
visible: boolean;
|
||||
screen: "team" | "plan";
|
||||
plans: readonly RegistrationPlanOptionData[];
|
||||
selectedPriceId: string;
|
||||
recommendedPriceId: string;
|
||||
officeSeatQuantity: number;
|
||||
fieldSeatQuantity: number;
|
||||
planAdviceLoading: boolean;
|
||||
planAdviceFailed: boolean;
|
||||
isSubmitting: boolean;
|
||||
acceptTerms: boolean;
|
||||
acceptPrivacy: boolean;
|
||||
captchaEnabled: boolean;
|
||||
captchaConfig: {
|
||||
provider?: "mcaptcha" | "cap";
|
||||
instanceUrl?: string;
|
||||
loginSiteKey?: string;
|
||||
};
|
||||
captchaResetKey?: string;
|
||||
captchaStatus: CaptchaStatus;
|
||||
requireEmailVerification: boolean;
|
||||
error?: string;
|
||||
onSelectPlan: (priceId: string) => void;
|
||||
onOfficeSeatQuantityChange: (quantity: number) => void;
|
||||
onFieldSeatQuantityChange: (quantity: number) => void;
|
||||
onAcceptTermsChange: (accepted: boolean) => void;
|
||||
onAcceptPrivacyChange: (accepted: boolean) => void;
|
||||
onCaptchaStatusChange: (status: CaptchaStatus) => void;
|
||||
onRetryPlanAdvice: () => void;
|
||||
onContinue: () => void;
|
||||
onBack: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const selectedPlan = plans.find((plan) => plan.priceId === selectedPriceId) ?? plans[0];
|
||||
const allConsents = acceptTerms && acceptPrivacy;
|
||||
const capProofPending = captchaEnabled && captchaConfig.provider === "cap" && captchaStatus !== "solved";
|
||||
|
||||
return (
|
||||
<div className={visible ? "flex w-full flex-col gap-6" : "hidden"} data-ui-id="ui.auth.register.planStep">
|
||||
{screen === "team" ? (
|
||||
<div className="flex w-full flex-col gap-6" data-ui-id="ui.auth.register.teamStep">
|
||||
<div className="flex w-full items-start gap-3">
|
||||
<IconWithBackground variant="information" size="medium" icon={<FeatherUsers />} />
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<span className="text-body-default-semibold-0 font-body-default-semibold-0 text-text-neutral-primary">{t("account.register.teamSizeTitle")}</span>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("account.register.teamSizeHint")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mobile:grid-cols-1 grid w-full grid-cols-2 gap-4">
|
||||
<div className="min-w-0 grow basis-0">
|
||||
<SeatQuantityStepper
|
||||
name="selectedOfficeSeatQuantity"
|
||||
label={t("account.register.officeUsersLabel")}
|
||||
description={t("account.register.officeUsersHint")}
|
||||
value={officeSeatQuantity}
|
||||
min={1}
|
||||
sliderMax={50}
|
||||
icon={<FeatherBriefcase />}
|
||||
disabled={isSubmitting}
|
||||
decreaseLabel={t("account.register.decreaseQuantity", { role: t("account.register.officeUsersLabel") })}
|
||||
increaseLabel={t("account.register.increaseQuantity", { role: t("account.register.officeUsersLabel") })}
|
||||
dataUiId="ui.auth.register.officeSeats"
|
||||
onChange={onOfficeSeatQuantityChange}
|
||||
/>
|
||||
</div>
|
||||
<div className="min-w-0 grow basis-0">
|
||||
<SeatQuantityStepper
|
||||
name="selectedFieldSeatQuantity"
|
||||
label={t("account.register.fieldUsersLabel")}
|
||||
description={t("account.register.fieldUsersHint")}
|
||||
value={fieldSeatQuantity}
|
||||
min={0}
|
||||
sliderMax={100}
|
||||
icon={<FeatherHardHat />}
|
||||
disabled={isSubmitting}
|
||||
decreaseLabel={t("account.register.decreaseQuantity", { role: t("account.register.fieldUsersLabel") })}
|
||||
increaseLabel={t("account.register.increaseQuantity", { role: t("account.register.fieldUsersLabel") })}
|
||||
dataUiId="ui.auth.register.fieldSeats"
|
||||
onChange={onFieldSeatQuantityChange}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<Card variant="neutral" size="small" className="gap-2 p-4">
|
||||
<div className="flex w-full items-center gap-2">
|
||||
<FeatherCheck className="text-body-default-regular-0 font-body-default-regular-0 text-icon-feedback-positive" />
|
||||
<span className="text-body-small-semibold-0 font-body-small-semibold-0 text-text-neutral-primary">
|
||||
{t("account.register.recommendationPromise")}
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary px-6">
|
||||
{t("account.register.recommendationPromiseHint")}
|
||||
</span>
|
||||
</Card>
|
||||
<Button
|
||||
type="button"
|
||||
size="large"
|
||||
className="w-full"
|
||||
icon={<FeatherArrowLeft className="rotate-180" />}
|
||||
disabled={isSubmitting || planAdviceLoading || planAdviceFailed}
|
||||
onClick={onContinue}
|
||||
data-ui-id="ui.auth.register.toPlanStep"
|
||||
>
|
||||
{t("account.register.continueToPlans")}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex w-full flex-col gap-4" data-ui-id="ui.auth.register.planSelection">
|
||||
<div className="flex w-full flex-col gap-1">
|
||||
<span className="text-body-small-semibold-0 font-body-small-semibold-0 text-text-neutral-primary">{t("account.register.planSelectionLabel")}</span>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("account.register.planSelectionHint")}
|
||||
</span>
|
||||
</div>
|
||||
{selectedPlan ? (
|
||||
<RadioCardGroup
|
||||
className="mobile:grid-cols-1 grid w-full grid-cols-3"
|
||||
value={selectedPriceId}
|
||||
onValueChange={onSelectPlan}
|
||||
aria-label={t("account.register.planSelectionLabel")}
|
||||
>
|
||||
{plans.map((plan) => (
|
||||
<RadioCardGroup.RadioCard key={plan.priceId} value={plan.priceId} disabled={isSubmitting || planAdviceLoading}>
|
||||
<div className="flex h-full w-full flex-col gap-4">
|
||||
<div className="flex w-full flex-col gap-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-heading- font-heading- text-text-neutral-primary">{t(plan.titleKey)}</span>
|
||||
{plan.priceId === recommendedPriceId ? (
|
||||
<BadgeFeedback farbe="subtle-brand-primary" size="small">
|
||||
{t("account.register.recommendedBadge")}
|
||||
</BadgeFeedback>
|
||||
) : null}
|
||||
</div>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("account.register.teamConfigured", { office: officeSeatQuantity, field: fieldSeatQuantity })}
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-heading-0 font-heading-0 text-text-neutral-primary">
|
||||
{t("account.register.planPriceMonthly", {
|
||||
price: formatters.currencyFromCents(plan.amountCents, plan.currency),
|
||||
})}
|
||||
</span>
|
||||
<div className="border-border-default flex w-full flex-col gap-2 border-0 border-t border-solid pt-3">
|
||||
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">
|
||||
{t("account.register.planIncluded", {
|
||||
office: plan.includedOfficeSeatQuantity,
|
||||
field: plan.includedFieldSeatQuantity,
|
||||
storage: plan.includedStorageGb,
|
||||
})}
|
||||
</span>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("account.register.planStorageGrowth", {
|
||||
storage: plan.storagePerAdditionalSeatGb,
|
||||
})}
|
||||
</span>
|
||||
{plan.extraOfficeSeatQuantity > 0 || plan.extraFieldSeatQuantity > 0 ? (
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("account.register.planExtrasIncluded", {
|
||||
office: plan.extraOfficeSeatQuantity,
|
||||
field: plan.extraFieldSeatQuantity,
|
||||
})}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</RadioCardGroup.RadioCard>
|
||||
))}
|
||||
</RadioCardGroup>
|
||||
) : null}
|
||||
{planAdviceLoading ? (
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary" role="status">
|
||||
{t("account.register.recommendationLoading")}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{planAdviceFailed ? (
|
||||
<div className="flex w-full flex-col items-start gap-3">
|
||||
<Alert
|
||||
variant="error"
|
||||
notDismissible
|
||||
title={t("account.register.recommendationErrorTitle")}
|
||||
description={t("account.register.recommendationErrorBody")}
|
||||
/>
|
||||
<Button type="button" variant="secondary" disabled={isSubmitting || planAdviceLoading} onClick={onRetryPlanAdvice}>
|
||||
{t("account.register.recommendationRetry")}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{screen === "plan" ? (
|
||||
<Card variant="default" size="medium" className="mobile:flex-col w-full flex-row items-start gap-6" data-ui-id="ui.auth.register.confirmation">
|
||||
{captchaEnabled ? (
|
||||
<div className="mobile:w-full flex w-[360px] flex-none flex-col gap-3">
|
||||
<div className="flex w-full items-start gap-3">
|
||||
<IconWithBackground variant="neutral" size="medium" icon={<FeatherLock />} />
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<span className="text-body-small-semibold-0 font-body-small-semibold-0 text-text-neutral-primary">{t("account.register.securityCheck")}</span>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("account.register.securityCheckHint")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{captchaResetKey ? (
|
||||
<Alert
|
||||
variant="neutral"
|
||||
notDismissible
|
||||
title={t("account.register.captchaReloadedTitle")}
|
||||
description={t("account.register.captchaReloadedBody")}
|
||||
/>
|
||||
) : null}
|
||||
<div className="border-border-default bg-surface-neutral-secondary flex w-full items-center justify-center rounded-md border border-solid px-3 py-3">
|
||||
<Captcha
|
||||
key={captchaResetKey ?? "initial-captcha"}
|
||||
enabled
|
||||
provider={captchaConfig.provider}
|
||||
instanceUrl={captchaConfig.instanceUrl}
|
||||
sitekey={captchaConfig.loginSiteKey}
|
||||
onStatusChange={onCaptchaStatusChange}
|
||||
/>
|
||||
</div>
|
||||
{captchaStatus === "error" ? (
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-feedback-negative" role="alert">
|
||||
{t("account.register.captchaClientError")}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="flex min-w-0 grow basis-0 flex-col gap-4">
|
||||
<div className="flex w-full flex-col items-start gap-3">
|
||||
<ConsentRow
|
||||
checked={acceptTerms}
|
||||
label={t("account.register.consentTerms")}
|
||||
href="/terms-and-conditions"
|
||||
linkLabel={t("account.register.consentTermsLink")}
|
||||
dataUiId="ui.auth.register.consentTerms"
|
||||
onChange={onAcceptTermsChange}
|
||||
/>
|
||||
<ConsentRow
|
||||
checked={acceptPrivacy}
|
||||
label={t("account.register.consentPrivacy")}
|
||||
href="/privacy-policy"
|
||||
linkLabel={t("account.register.privacyPolicy")}
|
||||
dataUiId="ui.auth.register.consentPrivacy"
|
||||
onChange={onAcceptPrivacyChange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<p className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="flex w-full flex-col items-start gap-2">
|
||||
<Button
|
||||
type="submit"
|
||||
size="large"
|
||||
className="w-full flex-none"
|
||||
icon={<FeatherCreditCard />}
|
||||
loading={isSubmitting}
|
||||
disabled={isSubmitting || !allConsents || planAdviceLoading || planAdviceFailed || capProofPending || !selectedPlan}
|
||||
data-ui-id="ui.auth.register.submit"
|
||||
>
|
||||
{t("account.register.continueWithPlan", { plan: selectedPlan ? t(selectedPlan.titleKey) : "" })}
|
||||
</Button>
|
||||
<div className="flex w-full items-start justify-center gap-1.5">
|
||||
{requireEmailVerification ? (
|
||||
<FeatherMail className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary mt-0.5" />
|
||||
) : (
|
||||
<FeatherLock className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary mt-0.5" />
|
||||
)}
|
||||
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary text-center">
|
||||
{t(requireEmailVerification ? "account.register.noPaymentYet" : "account.register.checkoutNext")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
className="self-start"
|
||||
variant="ghost"
|
||||
icon={<FeatherArrowLeft />}
|
||||
onClick={onBack}
|
||||
disabled={isSubmitting}
|
||||
data-ui-id={screen === "plan" ? "ui.auth.register.backToTeam" : "ui.auth.register.backToAccount"}
|
||||
>
|
||||
{t(screen === "plan" ? "account.register.backToTeam" : "account.register.backToAccount")}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ConsentRow({
|
||||
checked,
|
||||
label,
|
||||
href,
|
||||
linkLabel,
|
||||
dataUiId,
|
||||
onChange,
|
||||
}: {
|
||||
checked: boolean;
|
||||
label: string;
|
||||
href: string;
|
||||
linkLabel: string;
|
||||
dataUiId: string;
|
||||
onChange: (checked: boolean) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex w-full items-center gap-2">
|
||||
<Checkbox label={label} hideLabel checked={checked} onCheckedChange={onChange} data-ui-id={dataUiId} />
|
||||
<div className="flex min-h-5 flex-wrap items-center gap-1">
|
||||
<span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">{t("account.register.consentAcceptPrefix")}</span>
|
||||
<a href={href} target="_blank" rel="noreferrer" className="no-underline">
|
||||
<LinkButton size="small" hideIcon>
|
||||
{linkLabel}
|
||||
</LinkButton>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SeatQuantityStepper({
|
||||
name,
|
||||
label,
|
||||
description,
|
||||
value,
|
||||
min,
|
||||
max = 10_000,
|
||||
sliderMax,
|
||||
icon,
|
||||
disabled,
|
||||
decreaseLabel,
|
||||
increaseLabel,
|
||||
dataUiId,
|
||||
onChange,
|
||||
}: {
|
||||
name: string;
|
||||
label: string;
|
||||
description: string;
|
||||
value: number;
|
||||
min: number;
|
||||
max?: number;
|
||||
sliderMax: number;
|
||||
icon: React.ReactNode;
|
||||
disabled: boolean;
|
||||
decreaseLabel: string;
|
||||
increaseLabel: string;
|
||||
dataUiId: string;
|
||||
onChange: (value: number) => void;
|
||||
}) {
|
||||
return (
|
||||
<Card size="small" variant="default" className="h-full justify-between gap-3 p-4" data-ui-id={dataUiId}>
|
||||
<div className="flex w-full items-start gap-3 px-1">
|
||||
<IconWithBackground variant="neutral" size="medium" icon={icon} />
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<span className="text-body-small-semibold-0 font-body-small-semibold-0 text-text-neutral-primary">{label}</span>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">{description}</span>
|
||||
</div>
|
||||
</div>
|
||||
<Slider
|
||||
min={min}
|
||||
max={sliderMax}
|
||||
step={1}
|
||||
value={[Math.min(value, sliderMax)]}
|
||||
valueText={value}
|
||||
description={value > sliderMax ? `${sliderMax}+` : undefined}
|
||||
disabled={disabled}
|
||||
onValueChange={(values) => onChange(values[0] ?? min)}
|
||||
aria-label={label}
|
||||
/>
|
||||
<div className="flex w-full items-center justify-between gap-3" role="group" aria-label={label}>
|
||||
<IconButton
|
||||
type="button"
|
||||
variant="tertiary"
|
||||
square
|
||||
size="medium"
|
||||
icon={<FeatherMinus />}
|
||||
aria-label={decreaseLabel}
|
||||
disabled={disabled || value <= min}
|
||||
onClick={() => onChange(Math.max(min, value - 1))}
|
||||
data-ui-id={`${dataUiId}.decrease`}
|
||||
/>
|
||||
<TextInput className="max-w-24" type="number">
|
||||
<TextInput.Input
|
||||
name={name}
|
||||
type="number"
|
||||
min={min}
|
||||
max={max}
|
||||
step={1}
|
||||
value={value}
|
||||
aria-label={label}
|
||||
disabled={disabled}
|
||||
onChange={(event) => {
|
||||
const nextValue = event.currentTarget.valueAsNumber;
|
||||
if (Number.isFinite(nextValue)) {
|
||||
onChange(Math.min(max, Math.max(min, nextValue)));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</TextInput>
|
||||
<IconButton
|
||||
type="button"
|
||||
variant="tertiary"
|
||||
square
|
||||
size="medium"
|
||||
icon={<FeatherPlus />}
|
||||
aria-label={increaseLabel}
|
||||
disabled={disabled || value >= max}
|
||||
onClick={() => onChange(Math.min(max, value + 1))}
|
||||
data-ui-id={`${dataUiId}.increase`}
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
+7
-1
@@ -110,7 +110,13 @@ export default function ResetPasswordScreen({
|
||||
/>
|
||||
</TextInput>
|
||||
</div>
|
||||
<Progress className="h-auto w-full flex-none" hideLabel value={strength} state={strength >= 80 ? "success" : undefined} />
|
||||
<Progress
|
||||
className="h-auto w-full flex-none"
|
||||
hideLabel
|
||||
label={t("account.register.passwordStrength")}
|
||||
value={strength}
|
||||
state={strength >= 80 ? "success" : undefined}
|
||||
/>
|
||||
<div className="flex w-full items-center justify-between">
|
||||
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
|
||||
{t("account.register.passwordStrength")}: {strengthLabel}
|
||||
|
||||
+5
-1
@@ -104,7 +104,11 @@ export default function RolesListView({
|
||||
{editable ? (
|
||||
<SubframeCore.DropdownMenu.Root>
|
||||
<SubframeCore.DropdownMenu.Trigger asChild>
|
||||
<IconButton icon={<FeatherMoreHorizontal />} data-ui-id="ui.settings.rolesAndPermissions.roles.rowActions" />
|
||||
<IconButton
|
||||
icon={<FeatherMoreHorizontal />}
|
||||
aria-label={`${t("shared.actions")}: ${roleDisplayName(role, t)}`}
|
||||
data-ui-id="ui.settings.rolesAndPermissions.roles.rowActions"
|
||||
/>
|
||||
</SubframeCore.DropdownMenu.Trigger>
|
||||
<SubframeCore.DropdownMenu.Portal>
|
||||
<SubframeCore.DropdownMenu.Content side="bottom" align="end" sideOffset={4} asChild>
|
||||
|
||||
+12
-23
@@ -5,6 +5,7 @@ import { FeatherAlertTriangle, FeatherLogOut, FeatherMonitor, FeatherShieldOff,
|
||||
import type { SessionListVM } from "@hivegrid/view-models";
|
||||
import { Button } from "~/ui/components/Button";
|
||||
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
|
||||
import { Card } from "~/ui/components/Card";
|
||||
|
||||
// D-P2 — Settings > Sicherheit nach Davids Subframe-"Session Management"-Design: Header (Titel + "Überall
|
||||
// abmelden") + Geräte-Card (Icon + Label/Standort + "Dieses Gerät"-Badge / "Abmelden") + Confirm-Overlay
|
||||
@@ -44,19 +45,11 @@ export default function SecuritySessionsScreen({
|
||||
const onlyThisDevice = ready && devices.length <= 1 && !vm.data.canRevokeOthers;
|
||||
|
||||
return (
|
||||
<div className="relative flex w-full flex-col items-center" data-ui-id="ui.settings.security.page">
|
||||
<div className="flex w-full max-w-[768px] flex-col items-start gap-8">
|
||||
{/* Header */}
|
||||
<div className="flex w-full items-start justify-between gap-4 mobile:flex-col">
|
||||
<div className="flex flex-col items-start gap-2">
|
||||
<span className="text-title-page font-title-page text-text-neutral-primary mobile:text-subtitle mobile:font-subtitle">
|
||||
{t("settings.security.title")}
|
||||
</span>
|
||||
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-tertiary">
|
||||
{t("settings.security.sessions.subtitle")}
|
||||
</span>
|
||||
</div>
|
||||
{ready && vm.data.canRevokeOthers ? (
|
||||
<div className="relative flex w-full flex-col" data-ui-id="ui.settings.security.page">
|
||||
<div className="flex w-full flex-col items-start gap-8">
|
||||
{/* Page headline (title/subtitle) lives in the route's shared PageHeader; only the page-level action stays here. */}
|
||||
{ready && vm.data.canRevokeOthers ? (
|
||||
<div className="flex w-full items-start justify-end mobile:flex-col">
|
||||
<Button
|
||||
variant="secondary"
|
||||
icon={<FeatherLogOut />}
|
||||
@@ -66,15 +59,11 @@ export default function SecuritySessionsScreen({
|
||||
>
|
||||
{t("settings.security.sessions.revokeAll")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Aktive Sitzungen */}
|
||||
<section
|
||||
className="flex w-full flex-col items-start rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-6 py-6 shadow-sm"
|
||||
data-ui-id="ui.settings.security.sessions"
|
||||
aria-label={t("settings.security.sessions.heading")}
|
||||
>
|
||||
<Card className="w-full" data-ui-id="ui.settings.security.sessions" aria-label={t("settings.security.sessions.heading")}>
|
||||
{!ready ? (
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("settings.security.sessions.empty")}
|
||||
@@ -120,7 +109,7 @@ export default function SecuritySessionsScreen({
|
||||
);
|
||||
})
|
||||
)}
|
||||
</section>
|
||||
</Card>
|
||||
|
||||
{onlyThisDevice ? (
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
@@ -154,7 +143,7 @@ export default function SecuritySessionsScreen({
|
||||
{t("settings.security.trustedDevices.forgetAll")}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex w-full flex-col items-start rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-6 py-6 shadow-sm">
|
||||
<Card className="w-full">
|
||||
{trustedDevices.map((device, index) => (
|
||||
<Fragment key={device.id}>
|
||||
{index > 0 ? <div className="flex h-px w-full flex-none flex-col items-start bg-border-default" /> : null}
|
||||
@@ -181,7 +170,7 @@ export default function SecuritySessionsScreen({
|
||||
</div>
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
+29
-6
@@ -7,6 +7,7 @@ import { Button } from "~/ui/components/Button";
|
||||
import { LinkButton } from "~/ui/components/LinkButton";
|
||||
import { Progress } from "~/ui/components/Progress";
|
||||
import { TextInput } from "~/ui/components/TextInput";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
|
||||
// Set-Password-Screen (WF-P2 / S01 "Neues Passwort setzen") nach Davids Subframe-Design: Card mit
|
||||
// "Neues Passwort festlegen" + Stärke-Anzeige + Bestätigung + "Passwort setzen", Sicherheits-Footer.
|
||||
@@ -40,6 +41,7 @@ export default function SetPasswordScreen({
|
||||
actionData: { error?: string; invitationAccepted?: boolean } | null | undefined;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { csrf } = useRootData();
|
||||
const navigation = useNavigation();
|
||||
const navigate = useNavigate();
|
||||
const isSubmitting = navigation.state !== "idle";
|
||||
@@ -85,11 +87,20 @@ export default function SetPasswordScreen({
|
||||
dataUiId="ui.auth.setPassword.existingUser"
|
||||
>
|
||||
<Form method="post" className="flex w-full flex-col gap-4" data-ui-id="ui.auth.setPassword.acceptForm">
|
||||
<Button type="submit" name="intent" value="set-password" className="h-9 w-full flex-none" loading={isSubmitting} disabled={isSubmitting} data-ui-id="ui.auth.setPassword.acceptSubmit">
|
||||
<input type="hidden" name="csrf" value={csrf ?? ""} readOnly />
|
||||
<Button
|
||||
type="submit"
|
||||
name="intent"
|
||||
value="set-password"
|
||||
className="h-9 w-full flex-none"
|
||||
loading={isSubmitting}
|
||||
disabled={isSubmitting}
|
||||
data-ui-id="ui.auth.setPassword.acceptSubmit"
|
||||
>
|
||||
{t("account.invitation.button")}
|
||||
</Button>
|
||||
{actionData?.error && navigation.state === "idle" ? (
|
||||
<p className="text-center text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative" role="alert">
|
||||
<p className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative text-center" role="alert">
|
||||
{actionData.error}
|
||||
</p>
|
||||
) : null}
|
||||
@@ -123,11 +134,15 @@ export default function SetPasswordScreen({
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<span className="w-full text-center text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary" data-ui-id="ui.auth.setPassword.invitedContext">
|
||||
<span
|
||||
className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary w-full text-center"
|
||||
data-ui-id="ui.auth.setPassword.invitedContext"
|
||||
>
|
||||
{`${t("shared.hi")} ${invitedName}, ${t("account.invitation.youWereInvited")} ${invitation.tenant.name}`}
|
||||
</span>
|
||||
|
||||
<Form id="setPasswordForm" method="post" noValidate className="flex w-full flex-col gap-5" data-ui-id="ui.auth.setPassword.form">
|
||||
<input type="hidden" name="csrf" value={csrf ?? ""} readOnly />
|
||||
<div className="flex w-full flex-col items-start gap-2">
|
||||
<TextInput className="h-auto w-full flex-none" fillContainer showLabel label={t("account.newPassword.passwordLabel")} type="password">
|
||||
<TextInput.Input
|
||||
@@ -147,7 +162,7 @@ export default function SetPasswordScreen({
|
||||
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
|
||||
{t("account.register.passwordStrength")}: {strengthLabel}
|
||||
</span>
|
||||
<span className="w-full text-body-extra-small-medium-150 font-body-extra-small-medium-150 text-text-neutral-tertiary">
|
||||
<span className="text-body-extra-small-medium-150 font-body-extra-small-medium-150 text-text-neutral-tertiary w-full">
|
||||
{t("account.setPassword.passwordHint")}
|
||||
</span>
|
||||
</div>
|
||||
@@ -164,12 +179,20 @@ export default function SetPasswordScreen({
|
||||
/>
|
||||
</TextInput>
|
||||
|
||||
<Button type="submit" name="intent" value="set-password" className="h-9 w-full flex-none" loading={isSubmitting} disabled={isSubmitting} data-ui-id="ui.auth.setPassword.submit">
|
||||
<Button
|
||||
type="submit"
|
||||
name="intent"
|
||||
value="set-password"
|
||||
className="h-9 w-full flex-none"
|
||||
loading={isSubmitting}
|
||||
disabled={isSubmitting}
|
||||
data-ui-id="ui.auth.setPassword.submit"
|
||||
>
|
||||
{t("account.setPassword.button")}
|
||||
</Button>
|
||||
|
||||
{actionData?.error && navigation.state === "idle" ? (
|
||||
<p className="text-center text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative" role="alert">
|
||||
<p className="text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative text-center" role="alert">
|
||||
{actionData.error}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
+37
-16
@@ -2,7 +2,6 @@ import { useSubmit } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
|
||||
import MyProducts from "~/components/core/settings/subscription/MyProducts";
|
||||
import MySubscriptionFeatures from "~/components/core/settings/subscription/MySubscriptionFeatures";
|
||||
import MyInvoices from "~/components/core/settings/subscription/MyInvoices";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import { TenantSubscriptionProductWithDetails } from "~/utils/db/subscriptions/tenantSubscriptionProducts.db.server";
|
||||
@@ -12,15 +11,25 @@ import type { CustomerBillingInvoiceDto } from "~/application/dtos/billing/Custo
|
||||
import type { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import type { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
||||
import PlansGrouped from "~/components/core/settings/subscription/plans/PlansGrouped";
|
||||
import SeatUsageSection from "~/components/core/settings/subscription/SeatUsageSection";
|
||||
import { Alert } from "~/ui/components/Alert";
|
||||
import type { SeatUsageVM, SubscriptionBannerTone, SubscriptionBannerVM } from "@hivegrid/view-models";
|
||||
|
||||
function bannerVariant(tone: SubscriptionBannerTone): "success" | "warning" | "error" {
|
||||
if (tone === "success") return "success";
|
||||
if (tone === "warning") return "warning";
|
||||
return "error";
|
||||
}
|
||||
|
||||
export default function SubscriptionSettings({
|
||||
mySubscription,
|
||||
myFeatures,
|
||||
myInvoices,
|
||||
availablePlans,
|
||||
currenciesAndPeriod,
|
||||
invoiceErrorKey,
|
||||
permissions,
|
||||
billingBanner,
|
||||
seatUsage,
|
||||
}: {
|
||||
mySubscription: TenantSubscriptionWithDetails | null;
|
||||
myFeatures: PlanFeatureUsageDto[];
|
||||
@@ -32,6 +41,9 @@ export default function SubscriptionSettings({
|
||||
};
|
||||
invoiceErrorKey?: string | null;
|
||||
permissions: { viewInvoices: boolean; manageSubscription: boolean };
|
||||
billingBanner?: SubscriptionBannerVM;
|
||||
seatUsage?: SeatUsageVM;
|
||||
storageLimitGb?: number | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const submit = useSubmit();
|
||||
@@ -57,6 +69,15 @@ export default function SubscriptionSettings({
|
||||
|
||||
return (
|
||||
<div className="space-y-4" data-ui-id="ui.subscription.page">
|
||||
{billingBanner?.status === "ready" ? (
|
||||
<Alert
|
||||
variant={bannerVariant(billingBanner.data.tone)}
|
||||
notDismissible
|
||||
title={t(billingBanner.data.titleKey)}
|
||||
description={t(billingBanner.data.descriptionKey)}
|
||||
data-ui-id="ui.subscription.statusBanner"
|
||||
/>
|
||||
) : null}
|
||||
<SettingSection
|
||||
title={t("settings.subscription.title")}
|
||||
description={
|
||||
@@ -69,6 +90,20 @@ export default function SubscriptionSettings({
|
||||
<MyProducts items={mySubscription?.products ?? []} onCancel={onCancel} />
|
||||
</SettingSection>
|
||||
|
||||
{seatUsage && seatUsage.status !== "idle" && (
|
||||
<>
|
||||
<div className="hidden sm:block" aria-hidden="true">
|
||||
<div className="py-4">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SettingSection title={t("settings.subscription.seats.title")} description={t("settings.subscription.seats.description")} className="">
|
||||
<SeatUsageSection vm={seatUsage} />
|
||||
</SettingSection>
|
||||
</>
|
||||
)}
|
||||
|
||||
{availablePlans.length > 0 && (
|
||||
<>
|
||||
<div className="hidden sm:block" aria-hidden="true">
|
||||
@@ -89,20 +124,6 @@ export default function SubscriptionSettings({
|
||||
</>
|
||||
)}
|
||||
|
||||
{myFeatures.length > 0 && (
|
||||
<>
|
||||
<div className="hidden sm:block" aria-hidden="true">
|
||||
<div className="py-4">
|
||||
<div className="border-border border-t"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SettingSection title={t("app.subscription.features.title")} description={t("app.subscription.features.description")} className="">
|
||||
<MySubscriptionFeatures features={myFeatures} withCurrentPlan={false} />
|
||||
</SettingSection>
|
||||
</>
|
||||
)}
|
||||
|
||||
{permissions.viewInvoices && (
|
||||
<>
|
||||
<div className="hidden sm:block" aria-hidden="true">
|
||||
|
||||
+5
-4
@@ -13,10 +13,10 @@ import SuccessModal, { RefSuccessModal } from "~/components/ui/modals/SuccessMod
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import UploadDocuments from "~/components/ui/uploaders/UploadDocument";
|
||||
import UploadImage from "~/components/ui/uploaders/UploadImage";
|
||||
import { i18nConfig } from "~/locale/i18n";
|
||||
import type { CurrentSessionSettings } from "~/routes/app.$tenant/settings/profile";
|
||||
import type { CurrentSessionSettings } from "~/routes/app.$tenant/settings/profile/index";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { UserIcon } from "~/components/ui/icons/vendor";
|
||||
import { defaultEnabledLocales } from "~/locale/i18n";
|
||||
|
||||
type UserProfileMfaStatus = {
|
||||
enabled: boolean;
|
||||
@@ -83,7 +83,8 @@ export default function UserProfileSettings({
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigation = useNavigation();
|
||||
const submit = useSubmit();
|
||||
const { csrf } = useRootData();
|
||||
const { csrf, enabledLocales } = useRootData();
|
||||
const selectableLocales = enabledLocales ?? defaultEnabledLocales;
|
||||
|
||||
const errorModal = useRef<RefErrorModal>(null);
|
||||
const successModal = useRef<RefSuccessModal>(null);
|
||||
@@ -431,7 +432,7 @@ export default function UserProfileSettings({
|
||||
required
|
||||
value={i18n.language}
|
||||
setValue={(e) => changedLocale(e?.toString() || "")}
|
||||
options={i18nConfig.supportedLngs.map((locale) => ({ value: locale, name: t("shared.locales." + locale) }))}
|
||||
options={selectableLocales.map((locale) => ({ value: locale, name: t("shared.locales." + locale) }))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+1
-1
@@ -40,7 +40,7 @@ vi.mock("@hivegrid/config", async () => {
|
||||
}),
|
||||
};
|
||||
});
|
||||
vi.mock("~/utils/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: () => ({ allowed: true }) }));
|
||||
vi.mock("~/services/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: vi.fn().mockResolvedValue({ allowed: true }) }));
|
||||
|
||||
import { getUserByEmail } from "~/utils/db/users.db.server";
|
||||
import AuthService from "./AuthService";
|
||||
|
||||
+203
-14
@@ -29,6 +29,9 @@ vi.mock("~/utils/session.server", () => ({
|
||||
setLoggedUser: vi.fn().mockResolvedValue({ userId: "u1", defaultTenantId: "t1", defaultTenant: { id: "t1", slug: "t1" } }),
|
||||
validateCSRFToken: vi.fn(),
|
||||
commitPendingMfaLoginCookie: vi.fn().mockResolvedValue("hivegrid_session=pending; Path=/; HttpOnly"),
|
||||
isPendingMfaLoginFresh: vi.fn().mockReturnValue(true),
|
||||
isPendingMfaPrimaryMethod: vi.fn((value: unknown) => ["admin-sso", "password", "magic-link", "password-reset", "invitation"].includes(String(value))),
|
||||
PENDING_MFA_PRIMARY_METHOD_KEY: "pendingMfaPrimaryMethod",
|
||||
}));
|
||||
vi.mock("~/services/auth/sessionLifecycle.server", () => ({ startServerSession: vi.fn().mockResolvedValue("server-token") }));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({ getTenant: vi.fn().mockResolvedValue({ id: "t1", slug: "t1" }) }));
|
||||
@@ -36,6 +39,14 @@ vi.mock("~/utils/db/appConfiguration.db.server", () => ({ getAppConfiguration: v
|
||||
vi.mock("~/utils/auth/passwordHasher.server", () => ({ verifyPassword: vi.fn().mockResolvedValue({ valid: true, rehashedHash: null }) }));
|
||||
vi.mock("~/modules/ipAddress/services/IpAddressService.server", () => ({ default: { log: vi.fn().mockResolvedValue(null) } }));
|
||||
vi.mock("~/services/auth/password-policy.server", () => ({ validatePassword: vi.fn().mockResolvedValue({ valid: true, errors: [] }) }));
|
||||
vi.mock("~/services/auth/admin-fallback.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/services/auth/admin-fallback.server")>("~/services/auth/admin-fallback.server");
|
||||
return {
|
||||
...actual,
|
||||
assertAdminFallbackLoginAllowedForIdentity: vi.fn(),
|
||||
};
|
||||
});
|
||||
vi.mock("~/modules/admin-sso/audit.server", () => ({ writeAdminSsoAuditEvent: vi.fn() }));
|
||||
vi.mock("~/services/auth/login-captcha-gate.server", () => ({
|
||||
clearFailedLogins: vi.fn(),
|
||||
getFailedLoginCount: vi.fn().mockReturnValue(0),
|
||||
@@ -57,7 +68,7 @@ vi.mock("~/utils/auth/mfa/challenge-rate-limit.server", () => ({
|
||||
}));
|
||||
vi.mock("~/utils/auth/mfa/trusted-device.server", () => ({
|
||||
isTrustedDevice: vi.fn().mockResolvedValue(false),
|
||||
rememberDeviceForUser: vi.fn().mockResolvedValue("hivegrid_trusted_device=marker; Path=/; HttpOnly"),
|
||||
rememberDeviceForUser: vi.fn().mockResolvedValue("__Host-hivegrid_trusted_device=marker; Path=/; HttpOnly; Secure"),
|
||||
}));
|
||||
vi.mock("@hivegrid/config", async () => {
|
||||
const actual = await vi.importActual<typeof import("@hivegrid/config")>("@hivegrid/config");
|
||||
@@ -65,17 +76,26 @@ vi.mock("@hivegrid/config", async () => {
|
||||
...actual,
|
||||
loadRequiredWebConfig: () => ({
|
||||
nodeEnv: "test",
|
||||
routing: { appBaseDomain: "example.com", webAppHost: "app.example.com", adminAppHost: "admin.example.com", apiHost: "api.example.com", protocol: "https" },
|
||||
routing: {
|
||||
appBaseDomain: "example.com",
|
||||
webAppHost: "app.example.com",
|
||||
adminAppHost: "admin.example.com",
|
||||
apiHost: "api.example.com",
|
||||
protocol: "https",
|
||||
},
|
||||
}),
|
||||
};
|
||||
});
|
||||
vi.mock("~/services/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: () => ({ allowed: true }) }));
|
||||
vi.mock("~/services/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: vi.fn().mockResolvedValue({ allowed: true }) }));
|
||||
|
||||
import { getUserByEmail, getUser, getUserTotpStatus, getActiveTotpSecretEncrypted, consumeUserMfaRecoveryCode } from "~/utils/db/users.db.server";
|
||||
import { createUserSession, getUserSession, commitPendingMfaLoginCookie } from "~/utils/session.server";
|
||||
import { createUserSession, getUserSession, commitPendingMfaLoginCookie, isPendingMfaLoginFresh } from "~/utils/session.server";
|
||||
import { verifyTotpCode } from "~/services/auth/totp.server";
|
||||
import { checkMfaChallengeRateLimit, recordFailedMfaChallengeAttempt, resetMfaChallengeRateLimit } from "~/utils/auth/mfa/challenge-rate-limit.server";
|
||||
import { isTrustedDevice, rememberDeviceForUser } from "~/utils/auth/mfa/trusted-device.server";
|
||||
import { verifyPassword } from "~/utils/auth/passwordHasher.server";
|
||||
import { AdminFallbackLoginRejected, assertAdminFallbackLoginAllowedForIdentity } from "~/services/auth/admin-fallback.server";
|
||||
import { writeAdminSsoAuditEvent } from "~/modules/admin-sso/audit.server";
|
||||
import AuthService from "./AuthService";
|
||||
|
||||
const getUserByEmailMock = vi.mocked(getUserByEmail);
|
||||
@@ -86,9 +106,13 @@ const consumeUserMfaRecoveryCodeMock = vi.mocked(consumeUserMfaRecoveryCode);
|
||||
const createUserSessionMock = vi.mocked(createUserSession);
|
||||
const getUserSessionMock = vi.mocked(getUserSession);
|
||||
const commitPendingMfaLoginCookieMock = vi.mocked(commitPendingMfaLoginCookie);
|
||||
const isPendingMfaLoginFreshMock = vi.mocked(isPendingMfaLoginFresh);
|
||||
const verifyTotpCodeMock = vi.mocked(verifyTotpCode);
|
||||
const checkMfaChallengeRateLimitMock = vi.mocked(checkMfaChallengeRateLimit);
|
||||
const isTrustedDeviceMock = vi.mocked(isTrustedDevice);
|
||||
const verifyPasswordMock = vi.mocked(verifyPassword);
|
||||
const assertAdminFallbackLoginAllowedForIdentityMock = vi.mocked(assertAdminFallbackLoginAllowedForIdentity);
|
||||
const writeAdminSsoAuditEventMock = vi.mocked(writeAdminSsoAuditEvent);
|
||||
|
||||
const baseUser = { id: "u1", email: "alice@example.com", passwordHash: "hash", admin: null, locale: "de", defaultTenantId: "t1" };
|
||||
|
||||
@@ -116,6 +140,7 @@ beforeEach(() => {
|
||||
createUserSessionMock.mockImplementation(async () => redirectResponse());
|
||||
isTrustedDeviceMock.mockResolvedValue(false);
|
||||
checkMfaChallengeRateLimitMock.mockResolvedValue({ allowed: true, remaining: 5, resetAt: new Date() } as never);
|
||||
isPendingMfaLoginFreshMock.mockReturnValue(true);
|
||||
});
|
||||
|
||||
describe("loginFromRequest — 2FA gate", () => {
|
||||
@@ -129,50 +154,214 @@ describe("loginFromRequest — 2FA gate", () => {
|
||||
expect(body.requiresMfa).toBe(true);
|
||||
expect(body.mfaVerifyPath).toBe("/login-mfa");
|
||||
expect(response.headers.get("Set-Cookie")).toContain("hivegrid_session=pending");
|
||||
expect(commitPendingMfaLoginCookieMock).toHaveBeenCalledWith(expect.any(Request), { userId: "u1", redirectTo: "" });
|
||||
expect(commitPendingMfaLoginCookieMock).toHaveBeenCalledWith(expect.any(Request), {
|
||||
userId: "u1",
|
||||
redirectTo: "",
|
||||
primaryMethod: "password",
|
||||
});
|
||||
expect(createUserSessionMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("skips the gate for a trusted device and issues a normal session", async () => {
|
||||
getUserTotpStatusMock.mockResolvedValue({ enabled: true } as never);
|
||||
isTrustedDeviceMock.mockResolvedValue(true);
|
||||
const request = new Request("https://app.example.com/login", { method: "POST" });
|
||||
|
||||
const response = await AuthService.loginFromRequest(new Request("https://app.example.com/login", { method: "POST" }), loginForm());
|
||||
const response = await AuthService.loginFromRequest(request, loginForm());
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(commitPendingMfaLoginCookieMock).not.toHaveBeenCalled();
|
||||
expect(createUserSessionMock).toHaveBeenCalledTimes(1);
|
||||
expect(createUserSessionMock).toHaveBeenCalledWith(expect.any(Object), expect.any(String), { request, rotate: true });
|
||||
});
|
||||
|
||||
it("logs a non-TOTP user straight in (regression: branch is additive)", async () => {
|
||||
getUserTotpStatusMock.mockResolvedValue({ enabled: false } as never);
|
||||
const request = new Request("https://app.example.com/login", { method: "POST" });
|
||||
|
||||
const response = await AuthService.loginFromRequest(new Request("https://app.example.com/login", { method: "POST" }), loginForm());
|
||||
const response = await AuthService.loginFromRequest(request, loginForm());
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(commitPendingMfaLoginCookieMock).not.toHaveBeenCalled();
|
||||
expect(createUserSessionMock).toHaveBeenCalledTimes(1);
|
||||
expect(createUserSessionMock).toHaveBeenCalledWith(expect.any(Object), expect.any(String), { request, rotate: true });
|
||||
});
|
||||
|
||||
it("blocks a resolved AdminUser on the public app host when emergency fallback is disabled", async () => {
|
||||
getUserByEmailMock.mockResolvedValue({ ...baseUser, admin: { userId: "u1" } } as never);
|
||||
assertAdminFallbackLoginAllowedForIdentityMock.mockImplementationOnce(() => {
|
||||
throw new AdminFallbackLoginRejected("disabled");
|
||||
});
|
||||
|
||||
const response = await AuthService.loginFromRequest(new Request("https://app.example.com/login", { method: "POST" }), loginForm());
|
||||
const body = (await response.json()) as Record<string, unknown>;
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(body.error).toBe("api.errors.invalidPassword");
|
||||
expect(getUserTotpStatusMock).not.toHaveBeenCalled();
|
||||
expect(commitPendingMfaLoginCookieMock).not.toHaveBeenCalled();
|
||||
expect(createUserSessionMock).not.toHaveBeenCalled();
|
||||
expect(writeAdminSsoAuditEventMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: "admin.login.fallback.failure",
|
||||
actorAdminUserId: "u1",
|
||||
meta: expect.objectContaining({ method: "password", reason: "disabled" }),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("allows an allowlisted AdminUser and audits only the completed session", async () => {
|
||||
getUserByEmailMock.mockResolvedValue({ ...baseUser, admin: { userId: "u1" } } as never);
|
||||
getUserTotpStatusMock.mockResolvedValue({ enabled: false } as never);
|
||||
createUserSessionMock.mockResolvedValueOnce(
|
||||
new Response(null, {
|
||||
status: 302,
|
||||
headers: { Location: "https://admin.example.com/dashboard", "Set-Cookie": "__Host-hivegrid_admin_session=signed; HttpOnly; Secure" },
|
||||
})
|
||||
);
|
||||
|
||||
const response = await AuthService.loginFromRequest(new Request("https://admin.example.com/login", { method: "POST" }), loginForm());
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(assertAdminFallbackLoginAllowedForIdentityMock).toHaveBeenCalledWith(expect.objectContaining({ email: "alice@example.com" }));
|
||||
expect(writeAdminSsoAuditEventMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: "admin.login.fallback.success",
|
||||
actorAdminUserId: "u1",
|
||||
meta: expect.objectContaining({ method: "password", severity: "warn" }),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps wrong-password responses identity-agnostic before evaluating admin fallback", async () => {
|
||||
getUserByEmailMock.mockResolvedValue({ ...baseUser, admin: { userId: "u1" } } as never);
|
||||
verifyPasswordMock.mockResolvedValueOnce({ valid: false, rehashedHash: null });
|
||||
|
||||
const response = await AuthService.loginFromRequest(new Request("https://app.example.com/login", { method: "POST" }), loginForm());
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(assertAdminFallbackLoginAllowedForIdentityMock).not.toHaveBeenCalled();
|
||||
expect(writeAdminSsoAuditEventMock).not.toHaveBeenCalled();
|
||||
expect(createUserSessionMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("verifyMfaLoginFromRequest", () => {
|
||||
beforeEach(() => {
|
||||
getUserSessionMock.mockResolvedValue(sessionMock({ pendingMfaUserId: "u1", pendingMfaRedirectTo: "" }) as never);
|
||||
getUserSessionMock.mockResolvedValue(
|
||||
sessionMock({
|
||||
pendingMfaUserId: "u1",
|
||||
pendingMfaRedirectTo: "",
|
||||
pendingMfaStartedAt: new Date().toISOString(),
|
||||
pendingMfaPrimaryMethod: "password",
|
||||
}) as never
|
||||
);
|
||||
getUserTotpStatusMock.mockResolvedValue({ enabled: true } as never);
|
||||
});
|
||||
|
||||
it("rejects an expired pending challenge before checking a second factor", async () => {
|
||||
isPendingMfaLoginFreshMock.mockReturnValueOnce(false);
|
||||
const form = new FormData();
|
||||
form.append("code", "123456");
|
||||
|
||||
await expect(AuthService.verifyMfaLoginFromRequest(new Request("https://app.example.com/login-mfa", { method: "POST" }), form)).rejects.toMatchObject({
|
||||
status: 302,
|
||||
});
|
||||
|
||||
expect(getUserMock).not.toHaveBeenCalled();
|
||||
expect(createUserSessionMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("completes the login on a valid TOTP code", async () => {
|
||||
getActiveTotpSecretEncryptedMock.mockResolvedValue("enc-secret");
|
||||
verifyTotpCodeMock.mockReturnValue(true);
|
||||
const form = new FormData();
|
||||
form.append("code", "123456");
|
||||
const request = new Request("https://app.example.com/login-mfa", { method: "POST" });
|
||||
|
||||
const response = await AuthService.verifyMfaLoginFromRequest(request, form);
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(verifyTotpCodeMock).toHaveBeenCalledWith("enc-secret", "123456");
|
||||
expect(resetMfaChallengeRateLimit).toHaveBeenCalled();
|
||||
expect(createUserSessionMock).toHaveBeenCalledWith(expect.any(Object), expect.any(String), { request, rotate: true });
|
||||
});
|
||||
|
||||
it("re-checks a password-fallback AdminUser after MFA and blocks a policy revoked during the challenge", async () => {
|
||||
getUserMock.mockResolvedValue({ ...baseUser, admin: { userId: "u1" } } as never);
|
||||
getActiveTotpSecretEncryptedMock.mockResolvedValue("enc-secret");
|
||||
verifyTotpCodeMock.mockReturnValue(true);
|
||||
assertAdminFallbackLoginAllowedForIdentityMock.mockImplementationOnce(() => {
|
||||
throw new AdminFallbackLoginRejected("disabled");
|
||||
});
|
||||
const form = new FormData();
|
||||
form.append("code", "123456");
|
||||
|
||||
await expect(AuthService.verifyMfaLoginFromRequest(new Request("https://app.example.com/login-mfa", { method: "POST" }), form)).rejects.toMatchObject({
|
||||
status: 302,
|
||||
});
|
||||
|
||||
expect(createUserSessionMock).not.toHaveBeenCalled();
|
||||
expect(writeAdminSsoAuditEventMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: "admin.login.fallback.failure",
|
||||
actorAdminUserId: "u1",
|
||||
meta: expect.objectContaining({ method: "password", stage: "mfa-complete", reason: "disabled" }),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("audits a completed allowlisted magic-link AdminUser MFA session", async () => {
|
||||
getUserMock.mockResolvedValue({ ...baseUser, admin: { userId: "u1" } } as never);
|
||||
getUserSessionMock.mockResolvedValue(
|
||||
sessionMock({
|
||||
pendingMfaUserId: "u1",
|
||||
pendingMfaRedirectTo: "",
|
||||
pendingMfaStartedAt: new Date().toISOString(),
|
||||
pendingMfaPrimaryMethod: "magic-link",
|
||||
}) as never
|
||||
);
|
||||
getActiveTotpSecretEncryptedMock.mockResolvedValue("enc-secret");
|
||||
verifyTotpCodeMock.mockReturnValue(true);
|
||||
createUserSessionMock.mockResolvedValueOnce(
|
||||
new Response(null, {
|
||||
status: 302,
|
||||
headers: { Location: "https://admin.example.com/dashboard", "Set-Cookie": "__Host-hivegrid_admin_session=signed; HttpOnly; Secure" },
|
||||
})
|
||||
);
|
||||
const form = new FormData();
|
||||
form.append("code", "123456");
|
||||
|
||||
const response = await AuthService.verifyMfaLoginFromRequest(new Request("https://admin.example.com/login-mfa", { method: "POST" }), form);
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(writeAdminSsoAuditEventMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: "admin.login.fallback.success",
|
||||
actorAdminUserId: "u1",
|
||||
meta: expect.objectContaining({ method: "magic-link", mfa: true, severity: "warn" }),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("allows signed Authentik MFA assurance without applying fallback policy", async () => {
|
||||
getUserMock.mockResolvedValue({ ...baseUser, admin: { userId: "u1" } } as never);
|
||||
getUserSessionMock.mockResolvedValue(
|
||||
sessionMock({
|
||||
pendingMfaUserId: "u1",
|
||||
pendingMfaRedirectTo: "",
|
||||
pendingMfaStartedAt: new Date().toISOString(),
|
||||
pendingMfaPrimaryMethod: "admin-sso",
|
||||
}) as never
|
||||
);
|
||||
getActiveTotpSecretEncryptedMock.mockResolvedValue("enc-secret");
|
||||
verifyTotpCodeMock.mockReturnValue(true);
|
||||
const form = new FormData();
|
||||
form.append("code", "123456");
|
||||
|
||||
const response = await AuthService.verifyMfaLoginFromRequest(new Request("https://app.example.com/login-mfa", { method: "POST" }), form);
|
||||
|
||||
expect(response.status).toBe(302);
|
||||
expect(verifyTotpCodeMock).toHaveBeenCalledWith("enc-secret", "123456");
|
||||
expect(resetMfaChallengeRateLimit).toHaveBeenCalled();
|
||||
expect(createUserSessionMock).toHaveBeenCalledTimes(1);
|
||||
expect(assertAdminFallbackLoginAllowedForIdentityMock).not.toHaveBeenCalled();
|
||||
expect(writeAdminSsoAuditEventMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("completes the login on a valid recovery code when TOTP fails", async () => {
|
||||
@@ -200,7 +389,7 @@ describe("verifyMfaLoginFromRequest", () => {
|
||||
const response = await AuthService.verifyMfaLoginFromRequest(new Request("https://app.example.com/login-mfa", { method: "POST" }), form);
|
||||
|
||||
expect(rememberDeviceForUser).toHaveBeenCalledWith({ request: expect.any(Request), userId: "u1" });
|
||||
expect(response.headers.getSetCookie?.().some((c) => c.includes("hivegrid_trusted_device")) ?? true).toBe(true);
|
||||
expect(response.headers.getSetCookie?.().some((c) => c.includes("__Host-hivegrid_trusted_device")) ?? true).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a wrong code without issuing a session", async () => {
|
||||
|
||||
+7
-2
@@ -49,8 +49,13 @@ vi.mock("@hivegrid/config", async () => {
|
||||
}),
|
||||
};
|
||||
});
|
||||
vi.mock("~/utils/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: () => ({ allowed: true }) }));
|
||||
vi.mock("~/services/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: () => ({ allowed: true }) }));
|
||||
vi.mock("~/services/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: vi.fn().mockResolvedValue({ allowed: true }) }));
|
||||
vi.mock("~/services/auth/login-captcha-gate.server", () => ({
|
||||
clearFailedLogins: vi.fn(),
|
||||
getFailedLoginCount: vi.fn().mockResolvedValue(0),
|
||||
loginRequiresCaptcha: vi.fn().mockReturnValue(false),
|
||||
recordFailedLogin: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/services/auth/password-policy.server", () => ({
|
||||
validatePassword: vi.fn(),
|
||||
}));
|
||||
|
||||
+55
-2
@@ -48,16 +48,24 @@ vi.mock("@hivegrid/config", async () => {
|
||||
}),
|
||||
};
|
||||
});
|
||||
vi.mock("~/utils/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: () => ({ allowed: true }) }));
|
||||
vi.mock("~/services/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: () => ({ allowed: true }) }));
|
||||
vi.mock("~/services/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: vi.fn().mockResolvedValue({ allowed: true }) }));
|
||||
vi.mock("~/services/auth/login-captcha-gate.server", () => ({
|
||||
clearFailedLogins: vi.fn(),
|
||||
getFailedLoginCount: vi.fn().mockResolvedValue(0),
|
||||
loginRequiresCaptcha: vi.fn().mockReturnValue(false),
|
||||
recordFailedLogin: vi.fn(),
|
||||
}));
|
||||
|
||||
import { getUserByEmail } from "~/utils/db/users.db.server";
|
||||
import { verifyPassword } from "~/utils/auth/passwordHasher.server";
|
||||
import { recordFailedLogin } from "~/services/auth/login-captcha-gate.server";
|
||||
import { setLoggedUser } from "~/utils/session.server";
|
||||
import IpAddressServiceServer from "~/modules/ipAddress/services/IpAddressService.server";
|
||||
import AuthService from "./AuthService";
|
||||
|
||||
const getUserByEmailMock = vi.mocked(getUserByEmail);
|
||||
const verifyPasswordMock = vi.mocked(verifyPassword);
|
||||
const recordFailedLoginMock = vi.mocked(recordFailedLogin);
|
||||
const setLoggedUserMock = vi.mocked(setLoggedUser);
|
||||
|
||||
function buildForm(): FormData {
|
||||
@@ -98,6 +106,8 @@ describe("AuthService magic-link-only account guard (#20)", () => {
|
||||
const body = await result.json();
|
||||
// Anti-enumeration: identical to the unknown-email / wrong-password path.
|
||||
expect(body.error).toBe("api.errors.invalidPassword");
|
||||
expect(body.fields).toEqual({ email: "invited@example.com" });
|
||||
expect(JSON.stringify(body)).not.toContain("anything-they-typed");
|
||||
expect(body.requiresMagicLink).toBeUndefined();
|
||||
expect(body.magicLinkHref).toBeUndefined();
|
||||
// Timing side-channel closed: the dummy-hash comparison runs anyway.
|
||||
@@ -105,4 +115,47 @@ describe("AuthService magic-link-only account guard (#20)", () => {
|
||||
// Critical: must never have created a session on a null-hash row.
|
||||
expect(setLoggedUserMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects a disabled account generically before creating a session", async () => {
|
||||
getUserByEmailMock.mockResolvedValue({
|
||||
id: "u-disabled",
|
||||
email: "invited@example.com",
|
||||
passwordHash: "$argon2id$valid",
|
||||
firstName: "Disabled",
|
||||
lastName: "User",
|
||||
active: false,
|
||||
pendingDeletion: false,
|
||||
pseudonymized: false,
|
||||
admin: null,
|
||||
locale: null,
|
||||
} as unknown as Awaited<ReturnType<typeof getUserByEmail>>);
|
||||
|
||||
const req = new Request("https://app.example.com/login", { method: "POST" });
|
||||
const result = (await AuthService.loginFromRequest(req, buildForm())) as Response;
|
||||
|
||||
expect(result.status).toBe(400);
|
||||
await expect(result.json()).resolves.toMatchObject({
|
||||
error: "api.errors.invalidPassword",
|
||||
fields: { email: "invited@example.com" },
|
||||
});
|
||||
expect(verifyPasswordMock).toHaveBeenCalledTimes(1);
|
||||
expect(recordFailedLoginMock).toHaveBeenCalledWith({
|
||||
request: req,
|
||||
identifier: "invited@example.com",
|
||||
});
|
||||
expect(setLoggedUserMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not expose an unexpected IP logging error to the user", async () => {
|
||||
getUserByEmailMock.mockResolvedValue(null);
|
||||
vi.mocked(IpAddressServiceServer.log).mockRejectedValueOnce(new Error("database connection details"));
|
||||
|
||||
const result = (await AuthService.loginFromRequest(
|
||||
new Request("https://app.example.com/login", { method: "POST" }),
|
||||
buildForm()
|
||||
)) as Response;
|
||||
|
||||
expect(result.status).toBe(400);
|
||||
await expect(result.json()).resolves.toEqual({ error: "shared.unexpectedError" });
|
||||
});
|
||||
});
|
||||
+793
-73
File diff suppressed because it is too large.
Load diff
+416
-86
@@ -1,9 +1,21 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import UserValidationUtils from "~/utils/app/UserValidationUtils";
|
||||
import { createLogLogin } from "~/utils/db/logs.db.server";
|
||||
import { getUserByEmail, getUser, getUserTotpStatus, getActiveTotpSecretEncrypted, consumeUserMfaRecoveryCode } from "~/utils/db/users.db.server";
|
||||
import { setLoggedUser, createUserSession, getUserInfo, getUserSession, validateCSRFToken, commitPendingMfaLoginCookie } from "~/utils/session.server";
|
||||
import { startServerSession } from "~/services/auth/sessionLifecycle.server";
|
||||
import {
|
||||
setLoggedUser,
|
||||
createUserSession,
|
||||
getUserInfo,
|
||||
getUserSession,
|
||||
validateCSRFToken,
|
||||
commitPendingMfaLoginCookie,
|
||||
isPendingMfaLoginFresh,
|
||||
isPendingMfaPrimaryMethod,
|
||||
PENDING_MFA_PRIMARY_METHOD_KEY,
|
||||
} from "~/utils/session.server";
|
||||
import { updateUserPassword } from "~/utils/db/users.db.server";
|
||||
import { verifyTotpCode } from "~/services/auth/totp.server";
|
||||
import {
|
||||
@@ -14,10 +26,16 @@ import {
|
||||
} from "~/utils/auth/mfa/challenge-rate-limit.server";
|
||||
import { isTrustedDevice, rememberDeviceForUser } from "~/utils/auth/mfa/trusted-device.server";
|
||||
import { verifyPassword } from "~/utils/auth/passwordHasher.server";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import { getRegistrationFormData, validateRegistration, createRegistrationForm } from "~/utils/services/authService";
|
||||
import { getRegistrationByToken, updateRegistration } from "~/utils/db/registration.db.server";
|
||||
import {
|
||||
createRegistrationForm,
|
||||
getRegistrationFormData,
|
||||
isSignupCreationRequestKey,
|
||||
RegistrationValidationError,
|
||||
resolvePendingRegistrationResendRecovery,
|
||||
validateRegistration,
|
||||
} from "~/utils/services/authService";
|
||||
import { getRegistrationVerificationStateByToken, updateRegistration } from "~/utils/db/registration.db.server";
|
||||
import { Params, redirect } from "react-router";
|
||||
import IpAddressServiceServer from "~/modules/ipAddress/services/IpAddressService.server";
|
||||
import { isCanonicalAdminHostRoute } from "~/utils/app/HostRouting.server";
|
||||
@@ -29,10 +47,28 @@ import { clearFailedLogins, getFailedLoginCount, loginRequiresCaptcha, recordFai
|
||||
import { getSecret, getSitekey, isCaptchaConfigured, resolveCaptchaConfig, verifyCaptchaToken } from "@hivegrid/captcha";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { validatePassword as validatePolicyPassword } from "~/services/auth/password-policy.server";
|
||||
import {
|
||||
AdminFallbackLoginRejected,
|
||||
assertAdminFallbackLoginAllowedForIdentity,
|
||||
isCompletedAdminFallbackLoginResponse,
|
||||
} from "~/services/auth/admin-fallback.server";
|
||||
import { writeAdminSsoAuditEvent } from "~/modules/admin-sso/audit.server";
|
||||
import { deriveVerificationCreationRequestKey } from "~/domain/tenant-bootstrap/signupCreationRequestKey.server";
|
||||
import {
|
||||
clearRegistrationResendRecovery,
|
||||
commitRegistrationResendRecovery,
|
||||
readRegistrationResendRecovery,
|
||||
} from "~/services/auth/registration-resend-recovery.server";
|
||||
|
||||
const authLogger = createScopedLogger("auth");
|
||||
|
||||
const DUMMY_PASSWORD_HASH = "$2a$10$7EqJtq98hPqEX7fNZaFWoOhi8VfIf6z9SjG8/aYx8vvjE5LiE3D0C";
|
||||
const DUMMY_PASSWORD_HASH = "$argon2id$v=19$m=19456,t=2,p=1$CGZ841jS/Rerhh41+cREiw$piaCzFMbzHjq946K2t0iN7iMI/389iUpLNm2HROGO4Y";
|
||||
const REGISTRATION_VERIFY_RATE_LIMIT = 5;
|
||||
const REGISTRATION_VERIFY_RATE_LIMIT_WINDOW_MS = 15 * 60 * 1000;
|
||||
|
||||
function registrationVerifyRateLimitIdentifier(token: string): string {
|
||||
return createHash("sha256").update("registration-verify:v1\0").update(token).digest("hex");
|
||||
}
|
||||
|
||||
// D1 — tenant-faehige Verify-Route, an die das Login nach Passwort-OK fuer den zweiten Faktor
|
||||
// weiterleitet (siehe routeModules/auth/login-mfa).
|
||||
@@ -56,38 +92,48 @@ function translateIpAddressError(t: (key: string) => string, error: string): str
|
||||
if (error === "unauthorized") {
|
||||
return t("admin.accounts.ipAddresses.errors.unauthorized");
|
||||
}
|
||||
return error;
|
||||
return t("shared.unexpectedError");
|
||||
}
|
||||
|
||||
// The demo-login gate is a RUNTIME switch, not a seeding switch. It used to ride
|
||||
// on SEED_DEMO_DATA / ALLOW_STAGING_DEMO_SEED / SEED_DEMO_PRO_MANAGED, but the
|
||||
// RLS deploy contract forbids every SEED_*-prefixed key on a runtime resource
|
||||
// (`assert-runtime-db-env` rejects them, and seeding is not approved under forced
|
||||
// RLS). Carrying the gate on those names made the staging demo accounts
|
||||
// unreachable the moment the contract was enforced. It now has its own name, so
|
||||
// enabling demo logins never implies enabling a seed path.
|
||||
//
|
||||
// SENTRY_ENVIRONMENT is still required to be `staging`: the flag alone must not be
|
||||
// able to unlock a demo account in production, even if someone sets it there.
|
||||
type DemoLoginEnvironment = {
|
||||
ALLOW_STAGING_DEMO_SEED?: string;
|
||||
SEED_DEMO_DATA?: string;
|
||||
SENTRY_ENVIRONMENT?: string;
|
||||
STAGING_DEMO_LOGIN_ENABLED?: string;
|
||||
};
|
||||
|
||||
export function isStagingDemoLoginAllowed(env?: DemoLoginEnvironment) {
|
||||
const demoLoginEnv = env ?? (process.env as DemoLoginEnvironment);
|
||||
return demoLoginEnv.SEED_DEMO_DATA === "true" && demoLoginEnv.ALLOW_STAGING_DEMO_SEED === "true";
|
||||
return demoLoginEnv.SENTRY_ENVIRONMENT?.trim() === "staging" && demoLoginEnv.STAGING_DEMO_LOGIN_ENABLED?.trim() === "true";
|
||||
}
|
||||
|
||||
export function isProductionTestAccountBlocked(email: string, env?: DemoLoginEnvironment) {
|
||||
const runtimeEnv = env ?? (process.env as DemoLoginEnvironment);
|
||||
if (blockedProductionSeedAccountEmails.has(email)) {
|
||||
return true;
|
||||
}
|
||||
if (guardedStagingDemoAccountEmails.has(email)) {
|
||||
return !isStagingDemoLoginAllowed(env);
|
||||
if (guardedStagingDemoAccountEmails.has(email) || email.endsWith("@mitarbeiter.example.test")) {
|
||||
return !isStagingDemoLoginAllowed(runtimeEnv);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async function getHome({ isAdmin, tenantId, request }: { isAdmin: boolean; tenantId: string; request: Request }) {
|
||||
async function getHome({ isAdmin, tenantSlug, request }: { isAdmin: boolean; tenantSlug?: string | null; request: Request }) {
|
||||
let appHome = "";
|
||||
const appConfiguration = await getAppConfiguration({ request });
|
||||
if (isAdmin) {
|
||||
appHome = absoluteAdminPath(loadRequiredWebConfig().routing, "dashboard");
|
||||
} else if (appConfiguration.app.features.tenantHome === "/:tenant/") {
|
||||
const tenant = await getTenant(tenantId);
|
||||
if (tenant) {
|
||||
appHome = absoluteAppPath(loadRequiredWebConfig().routing, tenant.slug, "dashboard");
|
||||
if (tenantSlug) {
|
||||
appHome = absoluteAppPath(loadRequiredWebConfig().routing, tenantSlug, "dashboard");
|
||||
} else {
|
||||
appHome = absoluteAppRootPath(loadRequiredWebConfig().routing);
|
||||
}
|
||||
@@ -97,6 +143,22 @@ async function getHome({ isAdmin, tenantId, request }: { isAdmin: boolean; tenan
|
||||
return appHome;
|
||||
}
|
||||
|
||||
function getRegistrationBillingDestination(
|
||||
tenantSlug: string,
|
||||
selectedSubscriptionPriceId: string,
|
||||
selectedOfficeSeatQuantity?: number,
|
||||
selectedFieldSeatQuantity?: number
|
||||
): string {
|
||||
const destination = new URL(absoluteAppPath(loadRequiredWebConfig().routing, tenantSlug, "settings/billing"));
|
||||
destination.searchParams.set("subscription_required", "1");
|
||||
destination.searchParams.set("selected_price", selectedSubscriptionPriceId);
|
||||
if (selectedOfficeSeatQuantity !== undefined && selectedFieldSeatQuantity !== undefined) {
|
||||
destination.searchParams.set("office_seats", String(selectedOfficeSeatQuantity));
|
||||
destination.searchParams.set("field_seats", String(selectedFieldSeatQuantity));
|
||||
}
|
||||
return destination.toString();
|
||||
}
|
||||
|
||||
function isSafeRelativeRedirect(redirectTo: string) {
|
||||
return redirectTo.startsWith("/") && !redirectTo.startsWith("//") && !redirectTo.includes("\\");
|
||||
}
|
||||
@@ -125,11 +187,13 @@ export async function getSafeLoginRedirect({
|
||||
redirectTo,
|
||||
isAdmin,
|
||||
defaultTenantId,
|
||||
defaultTenantSlug,
|
||||
fallback,
|
||||
}: {
|
||||
redirectTo: string;
|
||||
isAdmin: boolean;
|
||||
defaultTenantId: string;
|
||||
defaultTenantSlug?: string | null;
|
||||
fallback: string;
|
||||
}) {
|
||||
if (!redirectTo || !isSafeRelativeRedirect(redirectTo)) {
|
||||
@@ -149,8 +213,7 @@ export async function getSafeLoginRedirect({
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const defaultTenant = defaultTenantId ? await getTenant(defaultTenantId) : null;
|
||||
const tenantSlug = defaultTenant?.slug;
|
||||
const tenantSlug = defaultTenantSlug ?? undefined;
|
||||
const targetsDefaultTenantId = Boolean(defaultTenantId && (redirectTo === `/${defaultTenantId}` || redirectTo.startsWith(`/${defaultTenantId}/`)));
|
||||
if (targetsDefaultTenantId) {
|
||||
return fallback;
|
||||
@@ -191,14 +254,16 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
throw new Error(t("auth:errors.invalidFormData"));
|
||||
}
|
||||
|
||||
const fields = { email, password };
|
||||
// Never return the submitted password in action data. React Router hydrates
|
||||
// error responses into the document, so only non-secret fields may be echoed.
|
||||
const fields = { email };
|
||||
const fieldErrors = {
|
||||
email: !UserValidationUtils.validateEmail(email) ? t("auth:errors.invalidEmail") : undefined,
|
||||
password: !UserValidationUtils.validatePassword(password) ? t("auth:errors.invalidPassword") : undefined,
|
||||
};
|
||||
if (Object.values(fieldErrors).some(Boolean)) return Response.json({ fieldErrors, fields }, { status: 400 });
|
||||
|
||||
const rateLimit = checkAuthRateLimit({
|
||||
const rateLimit = await checkAuthRateLimit({
|
||||
request,
|
||||
action: "login",
|
||||
identifier: email,
|
||||
@@ -212,7 +277,7 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
// Brute-force soft gate: after repeated failures per IP+email, require the
|
||||
// configured self-hosted captcha before checking the password.
|
||||
const captchaConfig = resolveCaptchaConfig(process.env);
|
||||
if (isCaptchaConfigured(captchaConfig) && loginRequiresCaptcha(getFailedLoginCount({ request, identifier: email }))) {
|
||||
if (isCaptchaConfigured(captchaConfig) && loginRequiresCaptcha(await getFailedLoginCount({ request, identifier: email }))) {
|
||||
const captchaOk = await verifyCaptchaToken({
|
||||
token: form.get("cap-token")?.toString() ?? form.get("mcaptcha__token")?.toString() ?? form.get("captchaToken")?.toString(),
|
||||
sitekey: getSitekey(captchaConfig, "login"),
|
||||
@@ -238,7 +303,7 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
}
|
||||
|
||||
if (isProductionTestAccountBlocked(email)) {
|
||||
return Response.json({ fields: { email, password }, error: t("auth:errors.productionTestAccountBlocked") }, { status: 400 });
|
||||
return Response.json({ fields, error: t("auth:errors.productionTestAccountBlocked") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
// Phase 01 / #20 — Magic-link-only accounts have `passwordHash = null`
|
||||
@@ -252,11 +317,38 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
// false for a null-hash row, so no session is ever issued. The magic-link
|
||||
// hint is surfaced generically on the /forgot-password flow, not here.
|
||||
const { valid: isCorrectPassword, rehashedHash } = await verifyPassword(password, user?.passwordHash ?? DUMMY_PASSWORD_HASH);
|
||||
if (!user || user.passwordHash === null || !isCorrectPassword) {
|
||||
recordFailedLogin({ request, identifier: email });
|
||||
// Keep disabled identities on the same generic credentials path so they
|
||||
// cannot be enumerated and never receive an immediately unusable session.
|
||||
if (!user || user.passwordHash === null || !isCorrectPassword || user.active === false) {
|
||||
await recordFailedLogin({ request, identifier: email });
|
||||
return Response.json({ fields, error: t("api.errors.invalidPassword") }, { status: 400 });
|
||||
}
|
||||
|
||||
// Admin identities may only use a password as the explicitly enabled,
|
||||
// allowlisted emergency fallback. This identity-based check also prevents
|
||||
// an AdminUser from bypassing the admin-host policy through an app-host
|
||||
// login; the resulting app cookie remains host-isolated from admin.
|
||||
const isAdminFallbackLogin = Boolean(user.admin);
|
||||
if (isAdminFallbackLogin) {
|
||||
try {
|
||||
assertAdminFallbackLoginAllowedForIdentity(user);
|
||||
} catch (error) {
|
||||
if (!(error instanceof AdminFallbackLoginRejected)) {
|
||||
throw error;
|
||||
}
|
||||
await recordFailedLogin({ request, identifier: email });
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.fallback.failure",
|
||||
actorAdminUserId: user.admin?.userId,
|
||||
request,
|
||||
meta: { reason: error.reason, email, method: "password" },
|
||||
});
|
||||
// Preserve the same public response as invalid credentials so resolving
|
||||
// an AdminUser never becomes an account-enumeration oracle.
|
||||
return Response.json({ fields, error: t("api.errors.invalidPassword") }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
if (rehashedHash) {
|
||||
// Drain a legacy bcrypt user to argon2 transparently on successful login.
|
||||
// Best-effort: never block the login on a rehash-persist failure.
|
||||
@@ -275,7 +367,7 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
}
|
||||
|
||||
// Erfolgreicher Login: Brute-Force-Failure-Counter zuruecksetzen (Captcha-Gate faellt wieder weg).
|
||||
clearFailedLogins({ request, identifier: email });
|
||||
await clearFailedLogins({ request, identifier: email });
|
||||
|
||||
// D1 (Produktentscheidung 18.06.) — 2FA-Login-Gate: TOTP-Nutzer erhalten mit Passwort allein
|
||||
// KEINE Session. Stattdessen wird ein signierter Pending-MFA-Zustand ins Cookie geschrieben
|
||||
@@ -283,26 +375,24 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
// vertrauenswuerdig markiertes Geraet (Trust-Device-Cookie) ueberspringt den zweiten Faktor.
|
||||
const totpStatus = await getUserTotpStatus(user.id);
|
||||
if (totpStatus?.enabled && !(await isTrustedDevice(request, user.id))) {
|
||||
const setCookie = await commitPendingMfaLoginCookie(request, { userId: user.id, redirectTo });
|
||||
const setCookie = await commitPendingMfaLoginCookie(request, { userId: user.id, redirectTo, primaryMethod: "password" });
|
||||
authLogger.info({ op: "login.mfaRequired", userId: user.id }, "Password accepted; awaiting second factor before issuing a session.");
|
||||
return Response.json(
|
||||
{ requiresMfa: true, redirectTo, mfaVerifyPath: LOGIN_MFA_VERIFY_PATH },
|
||||
{ status: 200, headers: { "Set-Cookie": setCookie } }
|
||||
);
|
||||
return Response.json({ requiresMfa: true, redirectTo, mfaVerifyPath: LOGIN_MFA_VERIFY_PATH }, { status: 200, headers: { "Set-Cookie": setCookie } });
|
||||
}
|
||||
|
||||
await createLogLogin(request, user);
|
||||
const userSession = await setLoggedUser(user);
|
||||
// const tenant = await getTenant(userSession.defaultTenantId);
|
||||
const { defaultTenant, ...userSessionData } = userSession;
|
||||
const appHome = await getHome({
|
||||
isAdmin: !!user.admin,
|
||||
tenantId: userSession.defaultTenantId,
|
||||
tenantSlug: defaultTenant?.slug,
|
||||
request,
|
||||
});
|
||||
const safeRedirectTo = await getSafeLoginRedirect({
|
||||
redirectTo,
|
||||
isAdmin: !!user.admin,
|
||||
defaultTenantId: userSession.defaultTenantId,
|
||||
defaultTenantId: userSessionData.defaultTenantId,
|
||||
defaultTenantSlug: defaultTenant?.slug,
|
||||
fallback: appHome,
|
||||
});
|
||||
// Phase 01 / #27 — soft-check the submitted password against the current
|
||||
@@ -333,19 +423,32 @@ async function loginFromRequest(request: Request, form: FormData) {
|
||||
"Password policy soft-check raised; falling back to policyOutdated=false."
|
||||
);
|
||||
}
|
||||
// R-P2a S4b — serverseitige Session-Zeile additiv anlegen (best-effort; ein Store-Fehler darf
|
||||
// den Login nicht blockieren) und ihren Token ins Cookie geben.
|
||||
const sessionToken = await startServerSession({ request, userId: user.id }).catch(() => null);
|
||||
return createUserSession(
|
||||
const response = await createUserSession(
|
||||
{
|
||||
...userInfo,
|
||||
...userSession,
|
||||
...userSessionData,
|
||||
lng: user.locale ?? userInfo.lng,
|
||||
passwordPolicyOutdated: passwordPolicyOutdated || undefined,
|
||||
sessionToken: sessionToken ?? undefined,
|
||||
},
|
||||
safeRedirectTo
|
||||
safeRedirectTo,
|
||||
isAdminFallbackLogin
|
||||
? {
|
||||
request,
|
||||
rotate: true,
|
||||
adminAuthenticationMethods: ["local-development", "mfa"],
|
||||
adminMfaAssuredAt: new Date(),
|
||||
}
|
||||
: { request, rotate: true }
|
||||
);
|
||||
if (isAdminFallbackLogin && isCompletedAdminFallbackLoginResponse(response)) {
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.fallback.success",
|
||||
actorAdminUserId: user.admin?.userId,
|
||||
request,
|
||||
meta: { email, severity: "warn", method: "password" },
|
||||
});
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -364,7 +467,10 @@ async function verifyMfaLoginFromRequest(request: Request, form: FormData) {
|
||||
const { t } = await getTranslations(request);
|
||||
const session = await getUserSession(request);
|
||||
const pendingMfaUserId = session.get("pendingMfaUserId");
|
||||
if (typeof pendingMfaUserId !== "string" || pendingMfaUserId.length === 0) {
|
||||
const pendingMfaStartedAt = session.get("pendingMfaStartedAt");
|
||||
const rawPendingMfaPrimaryMethod = session.get(PENDING_MFA_PRIMARY_METHOD_KEY);
|
||||
const pendingMfaPrimaryMethod = isPendingMfaPrimaryMethod(rawPendingMfaPrimaryMethod) ? rawPendingMfaPrimaryMethod : undefined;
|
||||
if (typeof pendingMfaUserId !== "string" || pendingMfaUserId.length === 0 || !isPendingMfaLoginFresh(pendingMfaStartedAt)) {
|
||||
// Kein laufender 2FA-Login (Cookie fehlt/abgelaufen) -> sauber zurueck zur Anmeldung.
|
||||
throw redirect("/login");
|
||||
}
|
||||
@@ -381,7 +487,10 @@ async function verifyMfaLoginFromRequest(request: Request, form: FormData) {
|
||||
const rateLimitKey = mfaChallengeRateLimitKey(request, user.id);
|
||||
const rateLimit = await checkMfaChallengeRateLimit(rateLimitKey);
|
||||
if (!rateLimit.allowed) {
|
||||
return Response.json({ error: t("account.loginMfa.errors.tooManyAttempts") }, { status: 429, headers: { "Retry-After": String(rateLimit.retryAfterSeconds) } });
|
||||
return Response.json(
|
||||
{ error: t("account.loginMfa.errors.tooManyAttempts") },
|
||||
{ status: 429, headers: { "Retry-After": String(rateLimit.retryAfterSeconds) } }
|
||||
);
|
||||
}
|
||||
|
||||
let verified = false;
|
||||
@@ -410,28 +519,70 @@ async function verifyMfaLoginFromRequest(request: Request, form: FormData) {
|
||||
|
||||
await resetMfaChallengeRateLimit(rateLimitKey);
|
||||
|
||||
// The pending cookie is signed and records which primary factor established
|
||||
// the challenge. Authentik is the only AdminUser path that may finish
|
||||
// without the emergency fallback policy; every other path is re-checked at
|
||||
// the last possible point so disabling/removing the allowlist during the MFA
|
||||
// challenge prevents a real admin session from being issued.
|
||||
const isAdminFallbackMfa = Boolean(user.admin && pendingMfaPrimaryMethod !== "admin-sso");
|
||||
if (isAdminFallbackMfa) {
|
||||
try {
|
||||
assertAdminFallbackLoginAllowedForIdentity(user);
|
||||
} catch (error) {
|
||||
if (!(error instanceof AdminFallbackLoginRejected)) {
|
||||
throw error;
|
||||
}
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.fallback.failure",
|
||||
actorAdminUserId: user.admin?.userId,
|
||||
request,
|
||||
meta: {
|
||||
reason: error.reason,
|
||||
email: user.email,
|
||||
method: pendingMfaPrimaryMethod ?? "unknown",
|
||||
stage: "mfa-complete",
|
||||
},
|
||||
});
|
||||
throw redirect("/login?error=fallback_disabled");
|
||||
}
|
||||
}
|
||||
|
||||
// Ab hier identisch zum normalen Login-Abschluss in loginFromRequest.
|
||||
const userInfo = await getUserInfo(request);
|
||||
await createLogLogin(request, user);
|
||||
const userSession = await setLoggedUser(user);
|
||||
const appHome = await getHome({ isAdmin: !!user.admin, tenantId: userSession.defaultTenantId, request });
|
||||
const { defaultTenant, ...userSessionData } = userSession;
|
||||
const appHome = await getHome({ isAdmin: !!user.admin, tenantSlug: defaultTenant?.slug, request });
|
||||
const rawRedirectTo = session.get("pendingMfaRedirectTo");
|
||||
const safeRedirectTo = await getSafeLoginRedirect({
|
||||
redirectTo: typeof rawRedirectTo === "string" ? rawRedirectTo : "",
|
||||
isAdmin: !!user.admin,
|
||||
defaultTenantId: userSession.defaultTenantId,
|
||||
defaultTenantId: userSessionData.defaultTenantId,
|
||||
defaultTenantSlug: defaultTenant?.slug,
|
||||
fallback: appHome,
|
||||
});
|
||||
const sessionToken = await startServerSession({ request, userId: user.id }).catch(() => null);
|
||||
const response = await createUserSession(
|
||||
{
|
||||
...userInfo,
|
||||
...userSession,
|
||||
...userSessionData,
|
||||
lng: user.locale ?? userInfo.lng,
|
||||
sessionToken: sessionToken ?? undefined,
|
||||
},
|
||||
safeRedirectTo
|
||||
safeRedirectTo,
|
||||
{ request, rotate: true }
|
||||
);
|
||||
if (isAdminFallbackMfa && isCompletedAdminFallbackLoginResponse(response)) {
|
||||
await writeAdminSsoAuditEvent({
|
||||
action: "admin.login.fallback.success",
|
||||
actorAdminUserId: user.admin?.userId,
|
||||
request,
|
||||
meta: {
|
||||
email: user.email,
|
||||
severity: "warn",
|
||||
method: pendingMfaPrimaryMethod ?? "unknown",
|
||||
mfa: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Trust-Device: dieses Geraet kuenftig ohne zweiten Faktor zulassen. Legt eine widerrufbare
|
||||
// TrustedDevice-Zeile an und gibt den Token als zusaetzliches Set-Cookie aus.
|
||||
@@ -444,84 +595,263 @@ async function verifyMfaLoginFromRequest(request: Request, form: FormData) {
|
||||
async function registerFromRequest(request: Request) {
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await getUserInfo(request);
|
||||
let creationRequestKey: string | undefined;
|
||||
let verificationFlowAttempted = false;
|
||||
let verificationEmail: string | undefined;
|
||||
let shouldResetCaptcha = false;
|
||||
try {
|
||||
await validateCSRFToken(request);
|
||||
const registrationData = await getRegistrationFormData(request);
|
||||
const result = await validateRegistration({ request, registrationData, addToTrialOrFreePlan: true });
|
||||
shouldResetCaptcha = registrationData.intent !== "resendVerification";
|
||||
if (registrationData.creationRequestKey && isSignupCreationRequestKey(registrationData.creationRequestKey)) {
|
||||
creationRequestKey = registrationData.creationRequestKey;
|
||||
}
|
||||
const isResendVerification = registrationData.intent === "resendVerification";
|
||||
let resendRecovery: { registrationId: string; catchUpOnly: boolean } | undefined;
|
||||
if (isResendVerification && registrationData.email) {
|
||||
const signedRecovery = await readRegistrationResendRecovery(request);
|
||||
if (signedRecovery?.email === registrationData.email.trim().toLowerCase()) {
|
||||
const resolvedRecovery = await resolvePendingRegistrationResendRecovery(signedRecovery);
|
||||
if (resolvedRecovery) {
|
||||
registrationData.creationRequestKey = resolvedRecovery.creationRequestKey;
|
||||
creationRequestKey = resolvedRecovery.creationRequestKey;
|
||||
resendRecovery = {
|
||||
registrationId: resolvedRecovery.registrationId,
|
||||
catchUpOnly: resolvedRecovery.catchUpOnly,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!isResendVerification && (!registrationData.acceptTerms || !registrationData.acceptPrivacy)) {
|
||||
throw new RegistrationValidationError("account.register.errors.acceptTermsAndPrivacy");
|
||||
}
|
||||
const result = await validateRegistration({
|
||||
request,
|
||||
registrationData,
|
||||
addToTrialOrFreePlan: false,
|
||||
requireSubscriptionSelection: true,
|
||||
...(isResendVerification ? { captchaAlreadyVerified: true } : {}),
|
||||
});
|
||||
if (result.verificationRequired) {
|
||||
await createRegistrationForm({ ...registrationData, email: result.email, ipAddress: result.ipAddress, recreateToken: false, request });
|
||||
return Response.json({ verificationEmailSent: true });
|
||||
verificationFlowAttempted = true;
|
||||
verificationEmail = result.email;
|
||||
if (!creationRequestKey) {
|
||||
throw new RegistrationValidationError("auth:errors.invalidFormData");
|
||||
}
|
||||
const createdRegistration = await createRegistrationForm({
|
||||
...registrationData,
|
||||
email: result.email,
|
||||
ipAddress: result.ipAddress,
|
||||
resendOnly: isResendVerification,
|
||||
request,
|
||||
creationRequestKey,
|
||||
selectedSubscriptionPriceId: result.selectedSubscriptionPriceId,
|
||||
selectedOfficeSeatQuantity: result.selectedOfficeSeatQuantity,
|
||||
selectedFieldSeatQuantity: result.selectedFieldSeatQuantity,
|
||||
...(resendRecovery ? { resendRecovery } : {}),
|
||||
});
|
||||
creationRequestKey = createdRegistration.creationRequestKey;
|
||||
return await registrationVerificationResponse(verificationEmail, creationRequestKey);
|
||||
} else if (result.registered) {
|
||||
const userSession = await setLoggedUser(result.registered.user);
|
||||
const home = await getHome({
|
||||
isAdmin: false,
|
||||
tenantId: userSession.defaultTenantId,
|
||||
request,
|
||||
});
|
||||
const sessionToken = await startServerSession({ request, userId: result.registered.user.id }).catch(() => null);
|
||||
return createUserSession(
|
||||
const { defaultTenant, ...userSessionData } = userSession;
|
||||
const tenantSlug = defaultTenant?.slug ?? result.registered.tenant.slug;
|
||||
const home = result.selectedSubscriptionPriceId
|
||||
? getRegistrationBillingDestination(tenantSlug, result.selectedSubscriptionPriceId, result.selectedOfficeSeatQuantity, result.selectedFieldSeatQuantity)
|
||||
: await getHome({
|
||||
isAdmin: false,
|
||||
tenantSlug,
|
||||
request,
|
||||
});
|
||||
const response = await createUserSession(
|
||||
{
|
||||
...userInfo,
|
||||
...userSession,
|
||||
...userSessionData,
|
||||
lng: result.registered.user.locale ?? userInfo.lng,
|
||||
sessionToken: sessionToken ?? undefined,
|
||||
},
|
||||
home
|
||||
home,
|
||||
{ request, rotate: true }
|
||||
);
|
||||
return await clearRegistrationRecoveryOnSessionResponse(response);
|
||||
}
|
||||
return Response.json({ error: t("shared.unknownError") }, { status: 400 });
|
||||
} catch (e: any) {
|
||||
return Response.json(
|
||||
{
|
||||
error: t("shared.unknownError"),
|
||||
...(creationRequestKey ? { creationRequestKey } : {}),
|
||||
...(shouldResetCaptcha ? { captchaResetKey: randomUUID() } : {}),
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
} catch (e: unknown) {
|
||||
// Intentionally do NOT log e.message verbatim — auth flow errors may
|
||||
// contain user-provided email/registration tokens. Log only the error
|
||||
// class and a short tag so we can still investigate via Sentry.
|
||||
authLogger.warn(
|
||||
{
|
||||
err: { name: e?.name ?? "Error", message: typeof e?.message === "string" ? "[redacted]" : "[unknown]" },
|
||||
err: { name: e instanceof Error ? e.name : "Error", message: e instanceof Error ? "[redacted]" : "[unknown]" },
|
||||
op: "verifyAndRegister",
|
||||
},
|
||||
"Auth verify-and-register failed"
|
||||
);
|
||||
return Response.json({ error: t(e.message) }, { status: 400 });
|
||||
if (verificationFlowAttempted && isHiddenRegistrationExistenceConflict(e) && creationRequestKey) {
|
||||
authLogger.info(
|
||||
{
|
||||
op: "registration.existence_hidden",
|
||||
reason: e instanceof RegistrationValidationError ? "registered" : "pending-conflict",
|
||||
},
|
||||
"Registration existence response normalized"
|
||||
);
|
||||
if (verificationEmail) {
|
||||
return await registrationVerificationResponse(verificationEmail, creationRequestKey);
|
||||
}
|
||||
}
|
||||
const publicError =
|
||||
e instanceof RegistrationValidationError ? t(e.i18nKey, e.i18nArgs ?? {}) : e instanceof CatalogError ? t(e.i18nKey) : t("shared.unknownError");
|
||||
return Response.json(
|
||||
{
|
||||
error: publicError,
|
||||
...(creationRequestKey ? { creationRequestKey } : {}),
|
||||
// CAP proofs are single-use. Any later validation failure after a
|
||||
// successful verification has consumed the proof as well, so every
|
||||
// failed initial registration must mount a fresh challenge for retry.
|
||||
...(shouldResetCaptcha ? { captchaResetKey: randomUUID() } : {}),
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function registrationVerificationResponse(email: string, creationRequestKey: string): Promise<Response> {
|
||||
return Response.json(
|
||||
{ verificationEmailSent: true, creationRequestKey },
|
||||
{
|
||||
headers: {
|
||||
"Cache-Control": "no-store",
|
||||
"Set-Cookie": await commitRegistrationResendRecovery({ email, creationRequestKey }),
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
async function clearRegistrationRecoveryOnSessionResponse(response: Response): Promise<Response> {
|
||||
response.headers.append("Set-Cookie", await clearRegistrationResendRecovery());
|
||||
return response;
|
||||
}
|
||||
|
||||
function isHiddenRegistrationExistenceConflict(error: unknown): boolean {
|
||||
return (
|
||||
(error instanceof RegistrationValidationError && error.i18nKey === "api.errors.userAlreadyRegistered") ||
|
||||
(error instanceof CatalogError && error.code === "foundation.idempotency_conflict")
|
||||
);
|
||||
}
|
||||
|
||||
async function verifyFromRequest({ request, params }: { request: Request; params: Params }) {
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const verificationToken = params.id ?? "";
|
||||
const rateLimit = await checkAuthRateLimit({
|
||||
request,
|
||||
action: "registration-verify",
|
||||
identifier: registrationVerifyRateLimitIdentifier(verificationToken),
|
||||
limit: REGISTRATION_VERIFY_RATE_LIMIT,
|
||||
windowMs: REGISTRATION_VERIFY_RATE_LIMIT_WINDOW_MS,
|
||||
});
|
||||
if (!rateLimit.allowed) {
|
||||
return Response.json(
|
||||
{ error: t("api.errors.tooManyRequests") },
|
||||
{
|
||||
status: 429,
|
||||
headers: {
|
||||
"Cache-Control": "no-store",
|
||||
"Retry-After": String(rateLimit.retryAfterSeconds),
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
const userInfo = await getUserInfo(request);
|
||||
|
||||
const registration = await getRegistrationByToken(params.id ?? "");
|
||||
if (!registration || registration.createdTenantId) {
|
||||
return Response.json({ error: t("api.errors.userAlreadyRegistered") }, { status: 400 });
|
||||
const verificationState = await getRegistrationVerificationStateByToken(verificationToken);
|
||||
if (verificationState.status !== "pending") {
|
||||
const errorKey =
|
||||
verificationState.status === "expired"
|
||||
? "account.verify.expiredLink"
|
||||
: verificationState.status === "used"
|
||||
? "account.verify.usedLink"
|
||||
: "account.verify.invalidLink";
|
||||
return Response.json({ error: t(errorKey) }, { status: 400 });
|
||||
}
|
||||
const registration = verificationState.registration;
|
||||
|
||||
let creationRequestKey: string | undefined;
|
||||
try {
|
||||
const registrationData = await getRegistrationFormData(request);
|
||||
registrationData.leadId = registration.leadConversionLeadId ?? undefined;
|
||||
registrationData.leadToken = registration.leadConversionToken ?? undefined;
|
||||
registrationData.leadPlanId = registration.leadConversionPlanId ?? undefined;
|
||||
const result = await validateRegistration({ request, registrationData, checkEmailVerification: false, addToTrialOrFreePlan: true });
|
||||
if (!result.registered) {
|
||||
return Response.json({ error: t("shared.unknownError") }, { status: 400 });
|
||||
const submittedData = await getRegistrationFormData(request);
|
||||
const expectedCreationRequestKey = deriveVerificationCreationRequestKey(registration.id);
|
||||
if (
|
||||
!submittedData.creationRequestKey ||
|
||||
!isSignupCreationRequestKey(submittedData.creationRequestKey) ||
|
||||
submittedData.creationRequestKey !== expectedCreationRequestKey
|
||||
) {
|
||||
throw new Error("Invalid verification creation request key");
|
||||
}
|
||||
await updateRegistration(registration.id, { createdTenantId: result.registered.tenant.id });
|
||||
const userSession = await setLoggedUser(result.registered.user);
|
||||
const appHome = await getHome({
|
||||
isAdmin: false,
|
||||
tenantId: userSession.defaultTenantId,
|
||||
creationRequestKey = expectedCreationRequestKey;
|
||||
// The URL token selects the persisted registration. Only the password and
|
||||
// captcha proof may come from the browser; identity and lead fields are
|
||||
// immutable here so hidden-form tampering cannot change the new account.
|
||||
const registrationData = {
|
||||
email: registration.email,
|
||||
password: submittedData.password,
|
||||
company: registration.company ?? undefined,
|
||||
firstName: registration.firstName,
|
||||
lastName: registration.lastName,
|
||||
slug: registration.slug ?? undefined,
|
||||
leadId: registration.leadConversionLeadId ?? undefined,
|
||||
leadToken: registration.leadConversionToken ?? undefined,
|
||||
leadPlanId: registration.leadConversionPlanId ?? undefined,
|
||||
selectedSubscriptionPriceId: registration.selectedSubscriptionPriceId ?? undefined,
|
||||
selectedOfficeSeatQuantity: registration.selectedOfficeSeatQuantity ?? undefined,
|
||||
selectedFieldSeatQuantity: registration.selectedFieldSeatQuantity ?? undefined,
|
||||
creationRequestKey,
|
||||
captchaToken: submittedData.captchaToken,
|
||||
};
|
||||
const result = await validateRegistration({
|
||||
request,
|
||||
registrationData,
|
||||
checkEmailVerification: false,
|
||||
captchaAlreadyVerified: true,
|
||||
addToTrialOrFreePlan: false,
|
||||
requireSubscriptionSelection: true,
|
||||
requireRegistrationSeatQuantities: registration.selectedOfficeSeatQuantity !== null && registration.selectedFieldSeatQuantity !== null,
|
||||
});
|
||||
const sessionToken = await startServerSession({ request, userId: result.registered.user.id }).catch(() => null);
|
||||
return createUserSession(
|
||||
if (!result.registered) {
|
||||
return Response.json({ error: t("shared.unknownError"), ...(creationRequestKey ? { creationRequestKey } : {}) }, { status: 400 });
|
||||
}
|
||||
// The compare-and-set below is the intentional replay boundary. Before it
|
||||
// commits, response-loss may safely retry the same key/payload. Afterwards
|
||||
// the token stays consumed; the committed password account recovers via
|
||||
// normal login instead of turning this verification URL into a login link.
|
||||
await updateRegistration(registration.id, { expectedToken: verificationToken }, { createdTenantId: result.registered.tenant.id });
|
||||
const userSession = await setLoggedUser(result.registered.user);
|
||||
const { defaultTenant, ...userSessionData } = userSession;
|
||||
const tenantSlug = defaultTenant?.slug ?? result.registered.tenant.slug;
|
||||
const appHome = result.selectedSubscriptionPriceId
|
||||
? getRegistrationBillingDestination(tenantSlug, result.selectedSubscriptionPriceId, result.selectedOfficeSeatQuantity, result.selectedFieldSeatQuantity)
|
||||
: await getHome({
|
||||
isAdmin: false,
|
||||
tenantSlug,
|
||||
request,
|
||||
});
|
||||
const response = await createUserSession(
|
||||
{
|
||||
...userInfo,
|
||||
...userSession,
|
||||
...userSessionData,
|
||||
lng: result.registered.user.locale ?? userInfo.lng,
|
||||
sessionToken: sessionToken ?? undefined,
|
||||
},
|
||||
appHome
|
||||
appHome,
|
||||
{ request, rotate: true }
|
||||
);
|
||||
return await clearRegistrationRecoveryOnSessionResponse(response);
|
||||
} catch {
|
||||
return Response.json({ error: t("shared.unknownError") }, { status: 400 });
|
||||
return Response.json({ error: t("shared.unknownError"), ...(creationRequestKey ? { creationRequestKey } : {}) }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user