Skip to content
Merged
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
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
125 changes: 125 additions & 0 deletions tests/js/login/components/login-captcha.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import React from 'react';
import { render, screen, fireEvent, act } from '@testing-library/react';

jest.mock('@marsidev/react-turnstile', () => require('../../helpers/turnstile_mock'));

import { mockTurnstile } from '../../helpers/turnstile_mock';
import { CAPTCHA_MESSAGES } from '../../../../resources/js/components/turnstile_captcha';
import PasswordInputForm from '../../../../resources/js/login/components/password_input_form';
import OTPInputForm from '../../../../resources/js/login/components/otp_input_form';

// Once the failed-attempts threshold is reached both login forms gate their native POST on
// a Turnstile token. Without one they must not call onAuthenticate and must ask the user to
// wait (or offer a retry when Turnstile fails), instead of "you must check CAPTCHA".

const COMMON = {
formAction: '/auth/login',
disableInput: false,
userNameValue: 'ada@example.com',
csrfToken: 'csrf-token',
captchaPublicKey: 'site-key',
loginAttempts: 3,
};

const FORMS = [
{
name: 'PasswordInputForm',
Form: PasswordInputForm,
submitLabel: /^continue$/i,
props: {
...COMMON,
showPassword: false,
passwordValue: 'secret-password',
passwordError: '',
onUserPasswordChange: jest.fn(),
handleClickShowPassword: jest.fn(),
handleMouseDownPassword: jest.fn(),
handleEmitOtpAction: jest.fn(),
forgotPasswordAction: '/auth/password/reset',
maxLoginFailedAttempts: 10,
userIsActive: true,
helpAction: '/help',
},
},
{
name: 'OTPInputForm',
Form: OTPInputForm,
submitLabel: /^continue$/i,
props: {
...COMMON,
otpCode: '123456',
otpError: '',
otpLength: 6,
otpLifetime: null,
codeVersion: 0,
onCodeChange: jest.fn(),
onReset: jest.fn(),
},
},
];

describe.each(FORMS)('$name captcha gate', ({ Form, props, submitLabel }) => {
let onAuthenticate;

const renderForm = (overrides = {}) =>
render(<Form {...props} onAuthenticate={onAuthenticate} {...overrides} />);
const clickSubmit = () => fireEvent.click(screen.getByRole('button', { name: submitLabel }));

beforeEach(() => {
mockTurnstile.clear();
// Returning false keeps jsdom from attempting the native navigation.
onAuthenticate = jest.fn(() => false);
// api.js loaded: retry resets the existing widget.
window.turnstile = {};
});

afterEach(() => {
delete window.turnstile;
});

it('has no captcha and submits normally below the failed-attempts threshold', () => {
renderForm({ shouldShowCaptcha: () => false });

expect(screen.queryByTestId('turnstile')).not.toBeInTheDocument();
clickSubmit();
expect(onAuthenticate).toHaveBeenCalledTimes(1);
});

it('does not authenticate before Turnstile issues a token and asks the user to wait', () => {
renderForm({ shouldShowCaptcha: () => true });

clickSubmit();

expect(onAuthenticate).not.toHaveBeenCalled();
expect(screen.getByRole('alert')).toHaveTextContent(CAPTCHA_MESSAGES.VERIFYING);
expect(screen.queryByText(/must check captcha/i)).not.toBeInTheDocument();
});

it('authenticates once Turnstile has issued a token', () => {
renderForm({ shouldShowCaptcha: () => true });

mockTurnstile.token = 'turnstile-token';
act(() => mockTurnstile.props.onSuccess('turnstile-token'));
clickSubmit();

expect(onAuthenticate).toHaveBeenCalledTimes(1);
});

it('offers a retry when Turnstile fails', () => {
renderForm({ shouldShowCaptcha: () => true });

act(() => mockTurnstile.props.onError('200500'));

expect(screen.getByText(CAPTCHA_MESSAGES.FAILED)).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /retry security check/i }));
expect(mockTurnstile.reset).toHaveBeenCalledTimes(1);
});

it('does not gate the submit when no site key is configured', () => {
renderForm({ shouldShowCaptcha: () => true, captchaPublicKey: '' });

expect(screen.queryByTestId('turnstile')).not.toBeInTheDocument();
clickSubmit();
expect(onAuthenticate).toHaveBeenCalledTimes(1);
});
});
Loading