Files
spsays-training/components/auth/login-form.tsx
T

94 lines
2.8 KiB
TypeScript

"use client";
/**
* LoginForm — pure form widget reused by both the dedicated /login page and
* the AuthGate modal that pops up when an unauthenticated user tries to use
* a protected feature.
*
* `onSuccess` is invoked once login completes. Callers decide what happens
* next (a page redirect, a modal close, etc.). The form itself doesn't
* navigate — that keeps it environment-agnostic.
*
* `forgotPasswordHref` is configurable so the modal can override (it may
* want to dismiss itself or open a different mode).
*/
import { useState } from "react";
import Link from "next/link";
import { useAuth } from "@/components/auth/auth-provider";
import { AuthError } from "@/lib/auth";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
export function LoginForm({
onSuccess,
forgotPasswordHref = "/forgot-password",
showForgotLink = true,
}: {
onSuccess?: () => void;
forgotPasswordHref?: string;
showForgotLink?: boolean;
}) {
const { logIn } = useAuth();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
async function onSubmit(e: React.SyntheticEvent) {
e.preventDefault();
setError(null);
setSubmitting(true);
try {
await logIn(email, password);
onSuccess?.();
} catch (err) {
setError(err instanceof AuthError ? err.message : "Login failed.");
} finally {
setSubmitting(false);
}
}
return (
<form onSubmit={onSubmit} className="space-y-5">
<div className="space-y-1.5">
<Label htmlFor="login-email">Email</Label>
<Input
id="login-email"
type="email"
autoComplete="email"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<Label htmlFor="login-password">Password</Label>
{showForgotLink ? (
<Link
href={forgotPasswordHref}
className="text-xs text-muted-foreground hover:text-foreground"
>
Forgot?
</Link>
) : null}
</div>
<Input
id="login-password"
type="password"
autoComplete="current-password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
{error ? <p className="text-sm text-destructive">{error}</p> : null}
<Button type="submit" disabled={submitting} className="w-full h-11 text-base">
{submitting ? "Logging in…" : "Log in"}
</Button>
</form>
);
}