// Define interface for props
interface RecaptchaEnterpriseContainerProps {
siteKey: DynamicValue<string>; // SiteKey as DynamicValue
token: EditableValue<string>; // EditableValue to interact with the Mendix attribute
onVerify: { execute: () => void }; // Callback for verification
}
// Component to handle reCAPTCHA Enterprise logic
const ReCaptchaEnterprise = ({
siteKey,
token,
onVerify,
}: RecaptchaEnterpriseContainerProps): ReactElement => {
const { executeRecaptcha } = useGoogleReCaptcha();
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [isInitialized, setIsInitialized] = useState<boolean>(false);
const handleVerify = async () => {
const siteKeyValue = siteKey.status === "available" && siteKey.value ? siteKey.value : "";
if (!executeRecaptcha) {
setErrorMessage("Recaptcha is not initialized. Please try again later.");
return;
}
try {
console.info("before execute:" + siteKeyValue);
const mtoken = await executeRecaptcha(siteKeyValue); // Verify CAPTCHA using the site key
console.info("after execute:" + siteKeyValue);
token.setValue(mtoken); // Update the Mendix token attribute
console.info("after setvalue:" + mtoken);
onVerify?.execute(); // Trigger the verification callback
console.info("after onverify");
console.info("Finished verifying captcha:", mtoken);
} catch (error) {
setErrorMessage("Failed to verify reCAPTCHA. Please try again.");
console.error("Error during reCAPTCHA verification:", error);
}
};
useEffect(() => {
if (executeRecaptcha) {
setIsInitialized(true);
handleVerify();
} else {
setErrorMessage("Recaptcha is not initialized. Please try again later.");
}
}, [executeRecaptcha]); // Dependency array includes executeRecaptcha to ensure it runs when executeRecaptcha is available
return (
<div>
{errorMessage && !isInitialized && <p style={{ color: "red" }}>{errorMessage}</p>}
</div>
);
};