Files
co-lite/solvway-admin-portal/app/components/users/SetPasswordButton.tsx
T

84 lines
3.0 KiB
TypeScript

"use client";
import { useState, type FormEvent } from "react";
import { Button } from "@/app/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog";
import { setAdminUserPassword } from "@/app/lib/services/adminUsers";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { PasswordFields } from "./PasswordFields";
/** "Set temporary password" on the user edit page: the admin types it; the user must change it at next sign-in. */
export function SetPasswordButton({ userId, onDone }: { userId: number; onDone: () => void }) {
const t = useT();
const [open, setOpen] = useState(false);
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
function close() {
// The password lives only in this state; clear it whenever the dialog closes.
setOpen(false);
setPassword("");
setConfirmPassword("");
setError(null);
}
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!password) return setError("UsrPasswordRequired");
if (password !== confirmPassword) return setError("UsrPasswordMismatch");
setSaving(true);
setError(null);
try {
await setAdminUserPassword(userId, password, confirmPassword);
close();
onDone();
} catch (err) {
setError(err instanceof Error ? err.message : "UsrSetPasswordFailed");
} finally {
setSaving(false);
}
}
return (
<>
<Button type="button" variant="outline" onClick={() => setOpen(true)}>
{t("UsrSetTempPassword")}
</Button>
{open && (
<Dialog open onOpenChange={(o) => !o && close()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{t("UsrSetTempPassword")}</DialogTitle>
</DialogHeader>
<form onSubmit={submit} className="space-y-4" noValidate>
<p className="text-sm text-muted-foreground">{t("UsrSetTempPasswordBody")}</p>
<PasswordFields
password={password}
confirmPassword={confirmPassword}
onPassword={setPassword}
onConfirmPassword={setConfirmPassword}
disabled={saving}
/>
{error && (
<div role="alert" className="rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">
{t(error)}
</div>
)}
<DialogFooter>
<Button type="button" variant="outline" onClick={close}>
{t("Cancel")}
</Button>
<Button type="submit" disabled={saving}>
{t("UsrSetPasswordSubmit")}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
)}
</>
);
}