ReCaptcha: Support usage in a wtform

This commit is contained in:
Adrian Moennich 2022-08-09 17:29:56 +02:00
parent aa9d125b05
commit ef7a90d352

View File

@ -6,7 +6,7 @@
// see the LICENSE file for more details.
import PropTypes from 'prop-types';
import React, {useEffect, useRef, useCallback} from 'react';
import React, {useState, useEffect, useRef, useCallback} from 'react';
import {useFormState, useForm} from 'react-final-form';
import ReCAPTCHA from 'react-google-recaptcha';
import {Message, Form} from 'semantic-ui-react';
@ -16,6 +16,27 @@ import {Translate} from 'indico/react/i18n';
import './Captcha.module.scss';
export default function Captcha({name, settings: {siteKey}, wtf}) {
return wtf ? (
<WTFCaptcha name={name} siteKey={siteKey} />
) : (
<FinalCaptcha name={name} siteKey={siteKey} />
);
}
Captcha.propTypes = {
name: PropTypes.string,
wtf: PropTypes.bool,
settings: PropTypes.shape({
siteKey: PropTypes.string.isRequired,
}).isRequired,
};
Captcha.defaultProps = {
name: 'captcha',
wtf: false,
};
function CaptchaField({onChange, siteKey, reCaptchaRef}) {
return <ReCAPTCHA sitekey={siteKey} onChange={onChange} ref={reCaptchaRef} />;
}
@ -23,11 +44,37 @@ function CaptchaField({onChange, siteKey, reCaptchaRef}) {
CaptchaField.propTypes = {
onChange: PropTypes.func.isRequired,
siteKey: PropTypes.string.isRequired,
reCaptchaRef: PropTypes.object.isRequired,
reCaptchaRef: PropTypes.object,
};
export default function Captcha({name, settings}) {
const {siteKey} = settings;
CaptchaField.defaultProps = {
reCaptchaRef: undefined,
};
function WTFCaptcha({name, siteKey}) {
const [response, setResponse] = useState('');
return (
<Message info style={{marginTop: 0}}>
<Message.Header>
<Translate>Confirm that you are not a robot</Translate> 🤖
</Message.Header>
<div>
<Form as="div" styleName="captcha">
<input type="hidden" name={name} value={response} />
<CaptchaField siteKey={siteKey} onChange={setResponse} />
</Form>
</div>
</Message>
);
}
WTFCaptcha.propTypes = {
name: PropTypes.string.isRequired,
siteKey: PropTypes.string.isRequired,
};
function FinalCaptcha({name, siteKey}) {
const reCaptchaRef = useRef(null);
const form = useForm();
const {submitErrors} = useFormState({
@ -68,11 +115,7 @@ export default function Captcha({name, settings}) {
);
}
Captcha.propTypes = {
name: PropTypes.string,
settings: PropTypes.object.isRequired,
};
Captcha.defaultProps = {
name: 'captcha',
FinalCaptcha.propTypes = {
name: PropTypes.string.isRequired,
siteKey: PropTypes.string.isRequired,
};