import type { BasePayload } from 'payload' import { userMeetsRole } from '../../access/predicates.js' import { formatDateTime } from '../../admin-i18n/t.js' import { serverText } from '../../integrations/texts.js' import { twoFactorSetupDeadline, twoFactorSetupState } from './secondFactor.js' import { TwoFactorResetButton } from './TwoFactorResetButton.js' type Props = { /** The account being shown. Injected by Payload into field server components. */ data?: { id?: number | string } & Record i18n?: { language?: string; t?: (key: never, vars?: Record) => string } payload?: BasePayload /** The account looking at it. */ user?: ({ id?: number | string } & Record) | null } /** * On an account in the panel (sidebar): where it stands with two-step * verification — set up, open until a date, or blocked because the time for * setup has passed — and, for an administrator looking at someone else's * account, the button that resets it / reopens setup. */ export async function TwoFactorStatusField({ data, i18n, payload, user }: Props) { if (!payload || !data?.id) {return null} const collection = (payload.config.custom as { ipal?: { twoFactor?: { collection?: string } } } | undefined)?.ipal?.twoFactor?.collection if (!collection) {return null} // The document data the panel passes hides `hasTotp` from everyone but the account itself (the 2FA // package's field access), so an admin would always read "set up". Ask the database: the secret is // only tested for presence, never shown. let stored: { totpSecret?: null | string; totpSetupFrom?: null | string } try { stored = (await payload.findByID({ id: data.id, collection: collection as never, depth: 0, overrideAccess: true, select: { totpSecret: true, totpSetupFrom: true } as never, showHiddenFields: true, })) as typeof stored } catch { return null } const account = { id: data.id, collection, email: data.email, hasTotp: Boolean(stored.totpSecret), totpSetupFrom: stored.totpSetupFrom } const state = twoFactorSetupState({ payload, user: account }) if (state === 'not-applicable') {return null} const deadline = twoFactorSetupDeadline({ payload, user: account }) const date = deadline ? formatDateTime(deadline.toISOString(), i18n?.language ?? 'en') : '' const status = state === 'set-up' ? serverText(i18n, 'twoFactorStatusOn') : state === 'exempt' ? serverText(i18n, 'twoFactorStatusExempt') : state === 'closed' ? serverText(i18n, 'twoFactorStatusClosed', { date }) : deadline ? serverText(i18n, 'twoFactorStatusOpen', { date }) : serverText(i18n, 'twoFactorStatusOpenNoLimit') const canReset = Boolean(user && user.id !== data.id && userMeetsRole({ payload, user }, 'admin')) return (
{serverText(i18n, 'twoFactorStatusLabel')}

{status}

{canReset && state !== 'exempt' && }
) }