Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
147 changes: 147 additions & 0 deletions resources/js/components/turnstile_captcha.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import React, { useEffect, useRef, useState } from "react";
import { Turnstile } from "@marsidev/react-turnstile";
import Button from "@material-ui/core/Button";
import Grid from "@material-ui/core/Grid";

// Turnstile does not always invoke onError when its iframe cannot be loaded (e.g. a network
// error reaching challenges.cloudflare.com): the widget just never renders and never issues a
// token. Without a token the backend rejects the form, so after this long without one we treat
// the security check as failed and let the user retry it.
export const CAPTCHA_LOAD_TIMEOUT_MS = 15000;

export const CAPTCHA_STATUS = {
VERIFYING: "verifying",
// Turnstile is showing a challenge the user has to complete: not a load failure.
INTERACTIVE: "interactive",
SOLVED: "solved",
FAILED: "failed",
};

export const CAPTCHA_MESSAGES = {
VERIFYING: "Please wait while we verify you are human, then submit again.",
INTERACTIVE: "Complete the security check, then submit again.",
FAILED:
"We couldn't load the security check. Check your connection or disable any content blocker, then retry.",
};

// Id of the <script> that @marsidev/react-turnstile injects for api.js (its default).
export const TURNSTILE_SCRIPT_ID = "cf-turnstile-script";

/**
* State for a Turnstile-protected form. With an empty siteKey the captcha is disabled:
* nothing renders and ensureToken() always lets the form through.
*/
export const useTurnstileCaptcha = (siteKey) => {
const ref = useRef(null);
const [status, setStatus] = useState(CAPTCHA_STATUS.VERIFYING);
const [submitAttempted, setSubmitAttempted] = useState(false);
// Bumped to remount the widget when api.js itself has to be loaded again.
const [widgetKey, setWidgetKey] = useState(0);

useEffect(() => {
if (!siteKey || status !== CAPTCHA_STATUS.VERIFYING) {
return undefined;
}
const timer = setTimeout(
() => setStatus(CAPTCHA_STATUS.FAILED),
CAPTCHA_LOAD_TIMEOUT_MS
);
Comment thread
romanetar marked this conversation as resolved.
Resolved
return () => clearTimeout(timer);
}, [siteKey, status]);

// Call before posting the form: true when it may be posted, otherwise it surfaces why not.
const ensureToken = () => {
if (!siteKey || ref.current?.getResponse()) {
return true;
}
setSubmitAttempted(true);
return false;
};

const onSuccess = () => {
setStatus(CAPTCHA_STATUS.SOLVED);
setSubmitAttempted(false);
};

const restart = () => {
setStatus(CAPTCHA_STATUS.VERIFYING);
ref.current?.reset();
Comment thread
romanetar marked this conversation as resolved.
Resolved
};

const retry = () => {
setSubmitAttempted(false);
if (!window.turnstile) {
// api.js never loaded (blocked or a network error), so there is no widget for reset()
// to act on, and the library will not inject the script again while the failed
// <script> element is still in the DOM. Drop it and remount the widget to reload it.
document.getElementById(TURNSTILE_SCRIPT_ID)?.remove();
setStatus(CAPTCHA_STATUS.VERIFYING);
setWidgetKey((key) => key + 1);
return;
}
restart();
};

const onBeforeInteractive = () => setStatus(CAPTCHA_STATUS.INTERACTIVE);

const onError = () => setStatus(CAPTCHA_STATUS.FAILED);

let message = null;
if (status === CAPTCHA_STATUS.FAILED) {
message = CAPTCHA_MESSAGES.FAILED;
} else if (submitAttempted && status === CAPTCHA_STATUS.VERIFYING) {
message = CAPTCHA_MESSAGES.VERIFYING;
} else if (submitAttempted && status === CAPTCHA_STATUS.INTERACTIVE) {
message = CAPTCHA_MESSAGES.INTERACTIVE;
}

return {
siteKey,
ref,
widgetKey,
status,
message,
ensureToken,
onSuccess,
onBeforeInteractive,
restart,
retry,
onError,
};
};

/**
* Renders the Turnstile widget plus its status message and retry action.
* `captcha` is the object returned by useTurnstileCaptcha().
*/
export const TurnstileCaptcha = ({ captcha, className, errorClassName }) => {
if (!captcha.siteKey) {
return null;
}
return (
<Grid container item justifyContent="center">
<Turnstile
key={captcha.widgetKey}
ref={captcha.ref}
className={className}
siteKey={captcha.siteKey}
options={{ responseFieldName: "cf-turnstile-response" }}
onSuccess={captcha.onSuccess}
onBeforeInteractive={captcha.onBeforeInteractive}
onExpire={captcha.restart}
onTimeout={captcha.restart}
onError={captcha.onError}
/>
{captcha.message && (
<div className={errorClassName} role="alert">
{captcha.message}
</div>
)}
{captcha.status === CAPTCHA_STATUS.FAILED && (
<Button type="button" size="small" color="primary" onClick={captcha.retry}>
Retry security check
</Button>
)}
</Grid>
);
};
25 changes: 9 additions & 16 deletions resources/js/login/components/otp_input_form.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import React from "react";
import { Turnstile } from "@marsidev/react-turnstile";
import Button from "@material-ui/core/Button";
import Link from "@material-ui/core/Link";
import OtpCodeInput from "./otp_code_input";
import useOtpCountdown from "./use_otp_countdown";
import { TurnstileCaptcha, useTurnstileCaptcha } from "../../components/turnstile_captcha";
import styles from "../login.module.scss";

const OTPInputForm = ({
Expand All @@ -20,13 +20,11 @@ const OTPInputForm = ({
csrfToken,
shouldShowCaptcha,
captchaPublicKey,
onChangeCaptchaProvider,
onExpireCaptchaProvider,
onErrorCaptchaProvider,
onReset,
loginAttempts,
}) => {
const showCaptcha = shouldShowCaptcha();
// The captcha only applies once the failed-attempts threshold is reached.
const captcha = useTurnstileCaptcha(shouldShowCaptcha() ? captchaPublicKey : "");
const { secondsLeft, expired } = useOtpCountdown(otpLifetime ?? 0, codeVersion);
// The countdown only renders when this page view knows when the code was
// issued (a fresh emitOTP in this session). After a failed-submit page
Expand All @@ -36,7 +34,7 @@ const OTPInputForm = ({
const blockExpired = countdownActive && expired;

const handleSubmit = (ev) => {
if (blockExpired || !onAuthenticate(ev.target))
if (blockExpired || !captcha.ensureToken() || !onAuthenticate(ev.target))
{
ev.preventDefault();
}
Expand Down Expand Up @@ -98,16 +96,11 @@ const OTPInputForm = ({
id="login_attempts"
name="login_attempts"
/>
{showCaptcha && captchaPublicKey && (
<Turnstile
className={styles.turnstile}
siteKey={captchaPublicKey}
options={{ responseFieldName: "cf-turnstile-response" }}
onSuccess={onChangeCaptchaProvider}
onExpire={onExpireCaptchaProvider}
onError={onErrorCaptchaProvider}
/>
)}
<TurnstileCaptcha
captcha={captcha}
className={styles.turnstile}
errorClassName={styles.error_label}
/>
</form>
);
};
Expand Down
25 changes: 10 additions & 15 deletions resources/js/login/components/password_input_form.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React from "react";
import { Turnstile } from "@marsidev/react-turnstile";
import TextField from "@material-ui/core/TextField";
import Button from "@material-ui/core/Button";
import Grid from "@material-ui/core/Grid";
Expand All @@ -12,6 +11,7 @@ import IconButton from "@material-ui/core/IconButton";
import ExistingAccountActions from "./existing_account_actions";
import styles from "../login.module.scss";
import HTMLRender from "../../shared/HTMLRender";
import { TurnstileCaptcha, useTurnstileCaptcha } from "../../components/turnstile_captcha";

const PasswordInputForm = ({
formAction,
Expand All @@ -27,9 +27,6 @@ const PasswordInputForm = ({
csrfToken,
shouldShowCaptcha,
captchaPublicKey,
onChangeCaptchaProvider,
onExpireCaptchaProvider,
onErrorCaptchaProvider,
handleEmitOtpAction,
forgotPasswordAction,
loginAttempts,
Expand All @@ -41,8 +38,11 @@ const PasswordInputForm = ({
// their save/update prompt off the browser's real submit event, and the backend
// login strategies respond with a redirect + flashed session state that only a
// top-level navigation consumes correctly.
// The captcha only applies once the failed-attempts threshold is reached.
const captcha = useTurnstileCaptcha(shouldShowCaptcha() ? captchaPublicKey : "");

const handleSubmit = (ev) => {
if (!onAuthenticate(ev.target)) {
if (!captcha.ensureToken() || !onAuthenticate(ev.target)) {
ev.preventDefault();
}
};
Expand Down Expand Up @@ -166,16 +166,11 @@ const PasswordInputForm = ({
id="login_attempts"
name="login_attempts"
/>
{shouldShowCaptcha() && captchaPublicKey && (
<Turnstile
className={styles.turnstile}
siteKey={captchaPublicKey}
options={{ responseFieldName: "cf-turnstile-response" }}
onSuccess={onChangeCaptchaProvider}
onExpire={onExpireCaptchaProvider}
onError={onErrorCaptchaProvider}
/>
)}
<TurnstileCaptcha
captcha={captcha}
className={styles.turnstile}
errorClassName={styles.error_label}
/>
<ExistingAccountActions
emitOtpAction={handleEmitOtpAction}
userName={userNameValue}
Expand Down
45 changes: 0 additions & 45 deletions resources/js/login/login.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React from "react";
import { Turnstile } from "@marsidev/react-turnstile";
import ReactDOM from "react-dom";
import Avatar from "@material-ui/core/Avatar";
import Button from "@material-ui/core/Button";
Expand Down Expand Up @@ -72,7 +71,6 @@ class LoginPage extends React.Component {
message: null,
severity: "info",
},
captcha_value: "",
showPassword: false,
disableInput: false,
authFlow: props.flow,
Expand Down Expand Up @@ -122,9 +120,6 @@ class LoginPage extends React.Component {
this.onValidateEmail = this.onValidateEmail.bind(this);
this.handleDelete = this.handleDelete.bind(this);
this.onAuthenticate = this.onAuthenticate.bind(this);
this.onChangeCaptchaProvider = this.onChangeCaptchaProvider.bind(this);
this.onExpireCaptchaProvider = this.onExpireCaptchaProvider.bind(this);
this.onErrorCaptchaProvider = this.onErrorCaptchaProvider.bind(this);
this.onUserPasswordChange = this.onUserPasswordChange.bind(this);
this.onOTPCodeChange = this.onOTPCodeChange.bind(this);
this.shouldShowCaptcha = this.shouldShowCaptcha.bind(this);
Expand Down Expand Up @@ -255,15 +250,6 @@ class LoginPage extends React.Component {
});
return false;
}

if (this.state.captcha_value == "" && this.shouldShowCaptcha()) {
this.setState({
...this.state,
disableInput: false,
errors: { ...this.state.errors, password: "you must check CAPTCHA" },
});
return false;
}
}

return true;
Expand All @@ -285,18 +271,6 @@ class LoginPage extends React.Component {
return true;
}

onChangeCaptchaProvider(value) {
this.setState({ ...this.state, captcha_value: value });
}

onExpireCaptchaProvider() {
this.setState({ ...this.state, captcha_value: "" });
}

onErrorCaptchaProvider() {
this.setState({ ...this.state, captcha_value: "" });
}

onHandleUserNameChange(ev) {
let { value, id } = ev.target;
this.setState({ ...this.state, user_name: value });
Expand Down Expand Up @@ -797,19 +771,6 @@ class LoginPage extends React.Component {
});
}

componentDidUpdate(prevProps, prevState) {
if (
this.state.user_verified &&
this.existingUserCanContinue() &&
prevState.authFlow !== this.state.authFlow
) {
this.setState({
...this.state,
captcha_value: "",
});
}
}

render() {
const showTwoFactorForm = this.state.authFlow === FLOW.MFA;
const showRecoveryForm = this.state.authFlow === FLOW.RECOVERY;
Expand Down Expand Up @@ -940,9 +901,6 @@ class LoginPage extends React.Component {
handleClickShowPassword={this.handleClickShowPassword}
handleMouseDownPassword={this.handleMouseDownPassword}
shouldShowCaptcha={this.shouldShowCaptcha}
onChangeCaptchaProvider={this.onChangeCaptchaProvider}
onExpireCaptchaProvider={this.onExpireCaptchaProvider}
onErrorCaptchaProvider={this.onErrorCaptchaProvider}
handleEmitOtpAction={this.handleEmitOtpAction}
/>
<HelpLinks
Expand Down Expand Up @@ -976,9 +934,6 @@ class LoginPage extends React.Component {
loginAttempts={this.props?.loginAttempts}
onCodeChange={this.onOTPCodeChange}
shouldShowCaptcha={this.shouldShowCaptcha}
onChangeCaptchaProvider={this.onChangeCaptchaProvider}
onExpireCaptchaProvider={this.onExpireCaptchaProvider}
onErrorCaptchaProvider={this.onErrorCaptchaProvider}
onReset={this.handleDelete}
onAuthenticate={this.onAuthenticate}
/>
Expand Down
Loading
Loading