Files
talktime/frontend/src/pages/AcceptInvitationPage.tsx
T
patrickandClaude Sonnet 5 f9451881c4 fix: invitation accept sent empty password string for existing users
AcceptInvitationPage's form always initializes password to "" via
react-hook-form defaultValues, even when the invited email already has
an account and the password field is hidden (requiresPassword=false).
The empty string was sent as-is instead of omitted, tripping the
backend's password.min(8).optional() — which only treats an absent key
as optional, not an empty string — and surfacing Zod's raw untranslated
message ("Too small: expected string to have >=8 characters") instead
of a friendly one.

Frontend: omit the password key entirely from the payload when
requiresPassword is false. Backend: defense in depth — treat an empty
string the same as omitted via a transform, and give the min(8) check
an actual German message for if this path is ever hit another way.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0143yYvjesjHndBACoweyK67
2026-09-12 00:10:45 +02:00

172 lines
5.7 KiB
TypeScript

import { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useAuth } from "@/lib/auth-context";
interface InvitationPreview {
email: string;
organizationName: string;
requiresPassword: boolean;
}
function buildSchema(requiresPassword: boolean) {
return z.object({
firstName: z.string().min(1, "Pflichtfeld"),
lastName: z.string().min(1, "Pflichtfeld"),
password: requiresPassword
? z.string().min(8, "Mindestens 8 Zeichen")
: z.string().optional(),
});
}
export function AcceptInvitationPage() {
const { token } = useParams<{ token: string }>();
const { setToken } = useAuth();
const navigate = useNavigate();
const [preview, setPreview] = useState<InvitationPreview | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [submitError, setSubmitError] = useState<string | null>(null);
useEffect(() => {
async function loadPreview() {
try {
const res = await fetch(`/api/invitations/${token}`);
if (!res.ok) {
const body = (await res.json()) as { error?: string };
throw new Error(body.error ?? `Fehler (${res.status})`);
}
setPreview((await res.json()) as InvitationPreview);
} catch (err) {
setLoadError((err as Error).message);
}
}
void loadPreview();
}, [token]);
const schema = buildSchema(preview?.requiresPassword ?? true);
const form = useForm<z.infer<typeof schema>>({
resolver: zodResolver(schema),
defaultValues: { firstName: "", lastName: "", password: "" },
});
async function onSubmit(values: z.infer<typeof schema>) {
setSubmitError(null);
try {
// When the invited email already has a login (requiresPassword=false),
// the hidden password field still holds its defaultValue of "" — sending
// that empty string (instead of omitting the key) hit the backend's
// min(8) check and surfaced its raw Zod message instead of a friendly one.
const payload = preview?.requiresPassword
? values
: { firstName: values.firstName, lastName: values.lastName };
const res = await fetch(`/api/invitations/${token}/accept`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!res.ok) {
const body = (await res.json()) as { error?: string };
throw new Error(body.error ?? `Fehler (${res.status})`);
}
const { token: authToken } = (await res.json()) as { token: string };
setToken(authToken);
navigate("/");
} catch (err) {
setSubmitError((err as Error).message);
}
}
if (loadError) {
return (
<main className="min-h-screen flex items-center justify-center p-6">
<p className="text-sm text-destructive">{loadError}</p>
</main>
);
}
if (!preview) {
return (
<main className="min-h-screen flex items-center justify-center p-6">
<p className="text-sm text-muted-foreground">Lädt…</p>
</main>
);
}
return (
<main className="min-h-screen flex items-center justify-center p-6">
<Card className="w-full max-w-sm">
<CardHeader>
<CardTitle>Einladung zu {preview.organizationName}</CardTitle>
</CardHeader>
<CardContent>
<p className="mb-4 text-sm text-muted-foreground">{preview.email}</p>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4" noValidate>
<FormField
control={form.control}
name="firstName"
render={({ field }) => (
<FormItem>
<FormLabel>Vorname</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="lastName"
render={({ field }) => (
<FormItem>
<FormLabel>Nachname</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{preview.requiresPassword && (
<FormField
control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>Passwort</FormLabel>
<FormControl>
<Input type="password" autoComplete="new-password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
)}
{submitError && <p className="text-sm text-destructive">{submitError}</p>}
<Button type="submit" className="w-full" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? "Wird angelegt…" : "Beitreten"}
</Button>
</form>
</Form>
</CardContent>
</Card>
</main>
);
}