"use client"; import { useState } from "react"; import { signIn } from "next-auth/react"; import { ErrorMessage } from "@/components/ui/ErrorMessage"; import { useTranslate } from "@/hooks/useTranslate"; import type { AppErrorType } from "@/types/global"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; interface LoginFormProps { from?: string; } export function LoginForm({ from }: LoginFormProps) { const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const { t } = useTranslate(); const getSafeRedirectPath = (path?: string) => { if (!path || !path.startsWith("/") || path.startsWith("//")) { return "/"; } return path; }; const handleSubmit = async (event: React.FormEvent) => { event.preventDefault(); setIsLoading(true); setError(null); const formData = new FormData(event.currentTarget); const email = formData.get("email") as string; const password = formData.get("password") as string; const remember = formData.get("remember") === "on"; try { const result = await signIn("credentials", { email, password, remember, redirect: false, }); if (!result || result.error || !result.ok) { setError({ code: "AUTH_INVALID_CREDENTIALS", name: "Login failed", message: "Email ou mot de passe incorrect", }); return; } const redirectPath = getSafeRedirectPath(from); window.location.href = redirectPath; } catch { setError({ code: "AUTH_FETCH_ERROR", name: "Login error", message: "Une erreur est survenue lors de la connexion", }); } finally { setIsLoading(false); } }; return (
{error && } ); }