payloadcms_otp_plugin
Version:
A comprehensive One-Time Password (OTP) authentication plugin for Payload CMS that enables secure passwordless authentication via SMS and email
93 lines (92 loc) • 3.36 kB
JavaScript
'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useState, useEffect } from 'react';
import './otp-view.scss';
import { useTranslation } from '@payloadcms/ui';
const TimerCountdown = ({ initialTimer = 10, onExpired, onReset, className = '', expiredMessage = 'The verification code has expired. Please request a new one.', activeMessage = 'Your OTP has been emailed and will expire at', showResendButton = true, onResend })=>{
const [timer, setTimer] = useState(initialTimer);
const [isExpired, setIsExpired] = useState(false);
const [isResending, setIsResending] = useState(false);
const { t } = useTranslation();
// Timer effect
useEffect(()=>{
if (timer > 0 && !isExpired) {
const interval = setInterval(()=>{
setTimer((prev)=>prev - 1);
}, 1000);
return ()=>clearInterval(interval);
} else if (timer === 0) {
setIsExpired(true);
onExpired?.();
}
}, [
timer,
isExpired,
onExpired
]);
// Reset timer when onReset is called
useEffect(()=>{
if (onReset) {
setTimer(initialTimer);
setIsExpired(false);
}
}, [
onReset,
initialTimer
]);
// Format timer display
const formatTime = (seconds)=>{
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
};
// Handle resend
const handleResend = async ()=>{
if (!onResend) return;
setIsResending(true);
try {
const success = await onResend();
if (success) {
setTimer(initialTimer);
setIsExpired(false);
}
} finally{
setIsResending(false);
}
};
return /*#__PURE__*/ _jsx("div", {
className: `timer-countdown ${className}`,
children: !isExpired ? /*#__PURE__*/ _jsxs("p", {
className: "timer-countdown__active",
role: "timer",
"aria-live": "polite",
children: [
activeMessage,
" ",
/*#__PURE__*/ _jsx("strong", {
children: formatTime(timer)
}),
"."
]
}) : /*#__PURE__*/ _jsx("div", {
className: "timer-countdown__expired",
children: /*#__PURE__*/ _jsxs("p", {
className: "timer-countdown__expired-message",
role: "alert",
children: [
expiredMessage,
showResendButton && onResend && /*#__PURE__*/ _jsx("button", {
className: "timer-countdown__resend-btn timer-countdown__resend-btn--underline",
onClick: handleResend,
disabled: isResending,
type: "button",
"aria-label": "Resend verification code",
children: isResending ? t("otp:sending") : t("otp:resend")
})
]
})
})
});
};
export default TimerCountdown;
//# sourceMappingURL=timer-count-down.js.map