Files
ncd-fe/app/soapbox/features/auth_login/components/captcha.tsx
2022-05-06 17:58:04 -05:00

119 lines
2.8 KiB
TypeScript

import { Map as ImmutableMap } from 'immutable';
import React, { useState, useEffect } from 'react';
import { FormattedMessage } from 'react-intl';
import { fetchCaptcha } from 'soapbox/actions/auth';
import { TextInput } from 'soapbox/features/forms';
import { useAppDispatch } from 'soapbox/hooks';
const noOp = () => {};
interface ICaptchaField {
name?: string,
value: string,
onChange?: React.ChangeEventHandler<HTMLInputElement>,
onFetch?: (captcha: ImmutableMap<string, any>) => void,
onFetchFail?: (error: Error) => void,
onClick?: React.MouseEventHandler,
refreshInterval?: number,
idempotencyKey: string,
}
const CaptchaField: React.FC<ICaptchaField> = ({
name,
value,
onChange = noOp,
onFetch = noOp,
onFetchFail = noOp,
onClick = noOp,
refreshInterval = 5*60*1000, // 5 minutes, Pleroma default
idempotencyKey,
}) => {
const dispatch = useAppDispatch();
const [captcha, setCaptcha] = useState(ImmutableMap<string, any>());
const [refresh, setRefresh] = useState<NodeJS.Timer | undefined>(undefined);
const getCaptcha = () => {
dispatch(fetchCaptcha()).then(response => {
const captcha = ImmutableMap<string, any>(response.data);
setCaptcha(captcha);
onFetch(captcha);
}).catch((error: Error) => {
onFetchFail(error);
});
};
const startRefresh = () => {
if (refreshInterval) {
const newRefresh = setInterval(getCaptcha, refreshInterval);
setRefresh(newRefresh);
}
};
const endRefresh = () => {
if (refresh) {
clearInterval(refresh);
}
};
useEffect(() => {
getCaptcha();
endRefresh();
startRefresh(); // Refresh periodically
return () => {
endRefresh();
};
}, [idempotencyKey]);
switch(captcha.get('type')) {
case 'native':
return (
<div>
<p>{<FormattedMessage id='registration.captcha.hint' defaultMessage='Click the image to get a new captcha' />}</p>
<NativeCaptchaField
captcha={captcha}
onChange={onChange}
onClick={onClick}
name={name}
value={value}
/>
</div>
);
case 'none':
default:
return null;
}
};
interface INativeCaptchaField {
captcha: ImmutableMap<string, any>,
onChange: React.ChangeEventHandler<HTMLInputElement>,
onClick: React.MouseEventHandler,
name?: string,
value: string,
}
const NativeCaptchaField: React.FC<INativeCaptchaField> = ({ captcha, onChange, onClick, name, value }) => (
<div className='captcha' >
<img alt='captcha' src={captcha.get('url')} onClick={onClick} />
<TextInput
placeholder='Enter the pictured text'
name={name}
value={value}
autoComplete='off'
autoCorrect='off'
autoCapitalize='off'
onChange={onChange}
required
/>
</div>
);
export {
CaptchaField as default,
NativeCaptchaField,
};