70 lines
2.4 KiB
TypeScript
70 lines
2.4 KiB
TypeScript
"use client";
|
|
|
|
import { useState } from "react";
|
|
import { signIn } from "next-auth/react";
|
|
import { useRouter } from "next/navigation";
|
|
import { useForm } from "react-hook-form";
|
|
import { zodResolver } from "@hookform/resolvers/zod";
|
|
import { z } from "zod";
|
|
import { Label } from "@/components/ui/label";
|
|
import { Input } from "@/components/ui/input";
|
|
import { Button } from "@/components/ui/button";
|
|
import { toast } from "sonner";
|
|
import { Loader2 } from "lucide-react";
|
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
|
|
|
const schema = z.object({
|
|
email: z.string().email("Bitte gültige E-Mail eingeben"),
|
|
password: z.string().min(8, "Mindestens 8 Zeichen")
|
|
});
|
|
|
|
type FormValues = z.infer<typeof schema>;
|
|
|
|
export function LoginForm() {
|
|
const router = useRouter();
|
|
const [loading, setLoading] = useState(false);
|
|
|
|
const { register, handleSubmit, formState: { errors } } = useForm<FormValues>({
|
|
resolver: zodResolver(schema)
|
|
});
|
|
|
|
const onSubmit = handleSubmit(async (values) => {
|
|
setLoading(true);
|
|
try {
|
|
const result = await signIn("credentials", {
|
|
email: values.email,
|
|
password: values.password,
|
|
redirect: false
|
|
});
|
|
if (!result || result.error) { toast.error("Anmeldung fehlgeschlagen"); return; }
|
|
toast.success("Erfolgreich angemeldet");
|
|
router.push("/admin/uebersicht");
|
|
router.refresh();
|
|
} finally { setLoading(false); }
|
|
});
|
|
|
|
return (
|
|
<Card className="w-full">
|
|
<CardHeader><CardTitle>Admin-Anmeldung</CardTitle></CardHeader>
|
|
<CardContent>
|
|
<form className="space-y-4" onSubmit={onSubmit}>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="email">E-Mail</Label>
|
|
<Input id="email" type="email" {...register("email")} />
|
|
{errors.email && <p className="text-xs text-destructive">{errors.email.message}</p>}
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="password">Passwort</Label>
|
|
<Input id="password" type="password" {...register("password")} />
|
|
{errors.password && <p className="text-xs text-destructive">{errors.password.message}</p>}
|
|
</div>
|
|
<Button className="w-full" type="submit" disabled={loading}>
|
|
{loading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
|
|
{loading ? "Anmeldung..." : "Einloggen"}
|
|
</Button>
|
|
</form>
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|