99 lines
2.5 KiB
TypeScript
99 lines
2.5 KiB
TypeScript
"use client";
|
|
|
|
import { useRouter } from "next/navigation";
|
|
import { useState, useTransition } from "react";
|
|
import type { Locale } from "@/lib/site-content";
|
|
|
|
type ApiResponse = {
|
|
ok: boolean;
|
|
error?: {
|
|
message?: string;
|
|
};
|
|
};
|
|
|
|
export function LoginForm({
|
|
locale,
|
|
labels,
|
|
}: {
|
|
locale: Locale;
|
|
labels: {
|
|
fieldLabel: string;
|
|
fieldHint: string;
|
|
submit: string;
|
|
submitting: string;
|
|
helperTitle: string;
|
|
helperBody: string;
|
|
commandLabel: string;
|
|
invalidKey: string;
|
|
};
|
|
}) {
|
|
const router = useRouter();
|
|
const [key, setKey] = useState("");
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [isPending, startTransition] = useTransition();
|
|
|
|
function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
|
|
event.preventDefault();
|
|
const trimmed = key.trim();
|
|
|
|
if (!trimmed) {
|
|
setError(labels.invalidKey);
|
|
return;
|
|
}
|
|
|
|
startTransition(async () => {
|
|
setError(null);
|
|
|
|
let payload: ApiResponse | null = null;
|
|
|
|
try {
|
|
const response = await fetch("/api/auth/login", {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({ key: trimmed }),
|
|
});
|
|
payload = (await response.json()) as ApiResponse;
|
|
|
|
if (!response.ok || !payload.ok) {
|
|
setError(payload.error?.message ?? labels.invalidKey);
|
|
return;
|
|
}
|
|
|
|
router.push(`/${locale}/console`);
|
|
router.refresh();
|
|
} catch (requestError) {
|
|
setError(requestError instanceof Error ? requestError.message : labels.invalidKey);
|
|
}
|
|
});
|
|
}
|
|
|
|
return (
|
|
<div className="login-form-stack">
|
|
<form className="auth-form" onSubmit={handleSubmit}>
|
|
<label className="field-label" htmlFor="popinewapi-key">
|
|
{labels.fieldLabel}
|
|
</label>
|
|
<input
|
|
aria-invalid={error ? "true" : "false"}
|
|
autoComplete="off"
|
|
className="text-input"
|
|
id="popinewapi-key"
|
|
inputMode="text"
|
|
onChange={(event) => setKey(event.target.value)}
|
|
placeholder="pk_live_..."
|
|
spellCheck={false}
|
|
type="password"
|
|
value={key}
|
|
/>
|
|
<p className="field-hint">{labels.fieldHint}</p>
|
|
{error ? <div className="status-banner status-banner-error">{error}</div> : null}
|
|
<button className="button button-dark" disabled={isPending} type="submit">
|
|
{isPending ? labels.submitting : labels.submit}
|
|
</button>
|
|
</form>
|
|
</div>
|
|
);
|
|
}
|