36 lines
1.4 KiB
TypeScript
36 lines
1.4 KiB
TypeScript
"use client";
|
|
|
|
import { useState } from "react";
|
|
|
|
import { browserFetch } from "../lib/api";
|
|
import { notifyAuthChanged } from "../lib/authEvents";
|
|
|
|
export default function LoginForm({ redirectTo = "/account" }: { redirectTo?: string }) {
|
|
const [error, setError] = useState("");
|
|
const [form, setForm] = useState({ email: "", password: "" });
|
|
|
|
async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
|
|
event.preventDefault();
|
|
setError("");
|
|
try {
|
|
const response = await browserFetch<{ user: { role: string } }>("/auth/login", {
|
|
method: "POST",
|
|
body: JSON.stringify(form)
|
|
});
|
|
notifyAuthChanged("login");
|
|
window.location.href = response.user.role === "admin" ? "/app/backoffice" : redirectTo;
|
|
} catch (submitError) {
|
|
setError(submitError instanceof Error ? submitError.message : "No se pudo entrar");
|
|
}
|
|
}
|
|
|
|
return (
|
|
<form className="stack" onSubmit={onSubmit}>
|
|
<input className="field" type="email" placeholder="Correo" value={form.email} onChange={(event) => setForm((current) => ({ ...current, email: event.target.value }))} required />
|
|
<input className="field" type="password" placeholder="Contrasena" value={form.password} onChange={(event) => setForm((current) => ({ ...current, password: event.target.value }))} required />
|
|
<button className="button button-primary" type="submit">Entrar</button>
|
|
{error ? <p className="muted">{error}</p> : null}
|
|
</form>
|
|
);
|
|
}
|