'use client' import { toast, useConfig, useTranslation } from '@payloadcms/ui' import { useState } from 'react' import { iaplT } from '../../admin-i18n/t.js' type Props = { /** `reopen`: the account has no TOTP (window passed or still open). `reset`: it has one (lost phone). */ kind: 'reopen' | 'reset' userId: number | string } /** The admin's button on an account: clears its TOTP so it can (or must) set it up again. */ export function TwoFactorResetButton({ kind, userId }: Props) { const { t } = useTranslation() const text = (key: Parameters[1]) => iaplT(t as never, key) const { config } = useConfig() const [busy, setBusy] = useState(false) const run = async () => { if (kind === 'reset' && !window.confirm(text('twoFactorResetConfirm'))) {return} setBusy(true) try { const res = await fetch(`${config.serverURL ?? ''}${config.routes?.api ?? '/api'}/ipal/two-factor/reset`, { body: JSON.stringify({ userId }), credentials: 'include', headers: { 'Content-Type': 'application/json' }, method: 'POST', }) const data = (await res.json()) as { message?: string; ok?: boolean } if (data.ok) { toast.success(data.message ?? text('twoFactorResetDone')) // The status next to this button is rendered on the server with the document: load it again. // (router.refresh() does not re-render a document's field components.) window.location.reload() } else { toast.error(data.message ?? text('twoFactorResetFailed')) } } catch { toast.error(text('twoFactorResetFailed')) } finally { setBusy(false) } } return ( ) }