"use client"; import { createBrowserClient } from "@supabase/ssr"; import { FormEvent, useEffect, useState } from "react"; import Link from "next/link"; import { useRouter } from "next/navigation"; type LoginFormProps = { redirectTo: string; role?: string; showForgot?: boolean; skipAuthedRedirect?: boolean; }; // Helper to prevent open redirect vulnerabilities const normalizeRedirect = (redirectTo: string) => { if (!redirectTo.startsWith("/") || redirectTo.startsWith("//")) { return "/courses"; } // Never redirect back into auth routes after successful login. if (redirectTo.startsWith("/auth/")) { return "/courses"; } return redirectTo; }; export default function LoginForm({ redirectTo, role, showForgot, skipAuthedRedirect }: LoginFormProps) { const router = useRouter(); const safeRedirect = normalizeRedirect(redirectTo); const isTeacher = role === "teacher"; const showForgotNotice = Boolean(showForgot); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [error, setError] = useState(null); const [loading, setLoading] = useState(false); useEffect(() => { if (skipAuthedRedirect) { return; } const supabase = createBrowserClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, ); supabase.auth.getUser().then(({ data }) => { if (data.user) { router.replace(safeRedirect); } }); }, [router, safeRedirect, skipAuthedRedirect]); // Construct the "Forgot Password" link to preserve context const forgotHref = `/auth/login?redirectTo=${encodeURIComponent(safeRedirect)}${isTeacher ? "&role=teacher" : "" }&forgot=1`; const onSubmit = async (event: FormEvent) => { event.preventDefault(); setError(null); setLoading(true); // 1. Initialize the Supabase Client (Browser side) const supabase = createBrowserClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY! ); // 2. Attempt Real Login const { error: signInError } = await supabase.auth.signInWithPassword({ email, password, }); if (signInError) { setLoading(false); setError(signInError.message); // e.g. "Invalid login credentials" return; } // 3. CRITICAL: Refresh the Server Context // This forces Next.js to re-run the Middleware and Server Components // so they see the new cookie immediately. router.refresh(); // 4. Navigate to the protected page and release button state. setLoading(false); router.replace(safeRedirect); }; return (

{isTeacher ? "Acceso Profesores" : "Iniciar Sesión"}

{isTeacher ? "Gestiona tus cursos y estudiantes." : "Ingresa para continuar aprendiendo."}

{showForgotNotice && (
El restablecimiento de contraseña no está disponible en este momento. Contacta a soporte.
)}
{error && (
{error}
)}
¿Olvidaste tu contraseña?
¿Nuevo aquí?{" "} Crear cuenta
{!isTeacher && (
¿Eres profesor?{" "} Ingresa aquí
)}
); }