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
17 changes: 15 additions & 2 deletions app/Services/Auth/UserService.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,22 @@ public function registerUser(array $payload, ?OAuth2OTP $otp = null):User
{
return $this->tx_service->transaction(function () use ($payload, $otp) {

Log::debug(sprintf("UserService::registerUser payload %s", json_encode($payload)));

$email = trim($payload['email']);

// The payload is the raw sign-up form (password, confirmation, captcha and CSRF
// tokens): log field names only, never values. Field names are client-controlled, so
// they are JSON-encoded to escape control characters. They stay in the message: with
// inline line breaks allowed (Laravel's default), Monolog turns an escaped newline in
// a JSON-encoded context back into a real one.
Log::debug
(
sprintf
(
"UserService::registerUser email %s fields %s",
json_encode($email),
json_encode(array_keys($payload))
)
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
$former_user = $this->user_repository->getByEmailOrName($email);

if (!is_null($former_user))
Expand Down
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
);
return () => clearTimeout(timer);
}, [siteKey, status]);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// 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();
};

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();
};
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

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>
);
};
54 changes: 20 additions & 34 deletions resources/js/email_verification/email_verification.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React, { useEffect, useRef, useState } from "react";
import React, { useEffect, useRef } from "react";
import ReactDOM from "react-dom";
import { Turnstile } from "@marsidev/react-turnstile";
import Button from "@material-ui/core/Button";
import Card from "@material-ui/core/Card";
import CardHeader from "@material-ui/core/CardHeader";
Expand All @@ -15,6 +14,7 @@ import { MuiThemeProvider, createTheme } from "@material-ui/core/styles";
import { useFormik } from "formik";
import { object, string, ref } from "yup";
import Banner from "../components/banner/banner";
import { TurnstileCaptcha, useTurnstileCaptcha } from "../components/turnstile_captcha";

import styles from "./email_verification.module.scss";

Expand All @@ -37,8 +37,7 @@ const EmailVerificationPage = ({
submitButtonText,
}) => {
const formEl = useRef(null);
const captcha = useRef(null);
const [captchaConfirmation, setCaptchaConfirmation] = useState(null);
const captcha = useTurnstileCaptcha(captchaPublicKey);

useEffect(() => {
if (emailVerificationError) {
Expand All @@ -56,20 +55,13 @@ const EmailVerificationPage = ({
initialValues: initialValues,
validationSchema: validationSchema,
onSubmit: () => {
if (!captcha.current?.getResponse()) {
setCaptchaConfirmation("Remember to check the captcha");
if (!captcha.ensureToken()) {
return;
}
doHtmlFormPost();
},
});

const onChangeCaptchaProvider = () => {
if (captcha.current?.getResponse()) {
setCaptchaConfirmation(null);
}
};

return (
<Container component="main" maxWidth="xs" className={styles.main_container}>
<CssBaseline />
Expand Down Expand Up @@ -120,22 +112,11 @@ const EmailVerificationPage = ({
/>
</Grid>
<Grid item container alignItems="center" justifyContent="center">
<Grid container item justify='center'>
<Turnstile
ref={captcha}
className={styles.turnstile}
siteKey={captchaPublicKey}
options={{ responseFieldName: "cf-turnstile-response" }}
onSuccess={onChangeCaptchaProvider}
onExpire={() => { captcha.current?.reset(); }}
onError={() => setCaptchaConfirmation('The security check encountered an error. Please refresh the page and try again.')}
/>
{captchaConfirmation && (
<div className={styles.error_label}>
{captchaConfirmation}
</div>
)}
</Grid>
<TurnstileCaptcha
captcha={captcha}
className={styles.turnstile}
errorClassName={styles.error_label}
/>
<Grid container item justify='center'>
<Button
variant="contained"
Expand Down Expand Up @@ -174,9 +155,14 @@ const theme = createTheme({
},
});

ReactDOM.render(
<MuiThemeProvider theme={theme}>
<EmailVerificationPage {...config} />
</MuiThemeProvider>,
document.querySelector("#root")
);
export { EmailVerificationPage };

const root = document.querySelector("#root");
if (root) {
ReactDOM.render(
<MuiThemeProvider theme={theme}>
<EmailVerificationPage {...config} />
</MuiThemeProvider>,
root
);
}
55 changes: 20 additions & 35 deletions resources/js/forgot_password/forgot_password.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React, { useEffect, useRef, useState } from "react";
import React, { useEffect, useRef } from "react";
import ReactDOM from "react-dom";
import { Turnstile } from "@marsidev/react-turnstile";
import Button from "@material-ui/core/Button";
import Card from "@material-ui/core/Card";
import CardHeader from "@material-ui/core/CardHeader";
Expand All @@ -15,6 +14,7 @@ import { MuiThemeProvider, createTheme } from "@material-ui/core/styles";
import { useFormik } from "formik";
import { object, string, ref } from "yup";
import Banner from "../components/banner/banner";
import { TurnstileCaptcha, useTurnstileCaptcha } from "../components/turnstile_captcha";

import styles from "./forgot_password.module.scss";

Expand All @@ -39,8 +39,7 @@ const ForgotPasswordPage = ({
submitButtonText,
}) => {
const formEl = useRef(null);
const captcha = useRef(null);
const [captchaConfirmation, setCaptchaConfirmation] = useState(null);
const captcha = useTurnstileCaptcha(captchaPublicKey);

useEffect(() => {
if (forgotPasswordError) {
Expand All @@ -58,21 +57,13 @@ const ForgotPasswordPage = ({
initialValues: initialValues,
validationSchema: validationSchema,
onSubmit: (values) => {
const turnstileResponse = captcha.current?.getResponse();
if (!turnstileResponse) {
setCaptchaConfirmation("Remember to check the captcha");
if (!captcha.ensureToken()) {
return;
}
doHtmlFormPost();
},
});

const onChangeCaptchaProvider = () => {
if (captcha.current?.getResponse()) {
setCaptchaConfirmation(null);
}
};

return (
<Container component="main" maxWidth="xs" className={styles.main_container}>
<CssBaseline />
Expand Down Expand Up @@ -136,22 +127,11 @@ const ForgotPasswordPage = ({
/>
</Grid>
<Grid item container alignItems="center" justifyContent="center">
<Grid container item justify='center'>
<Turnstile
ref={captcha}
className={styles.turnstile}
siteKey={captchaPublicKey}
options={{ responseFieldName: "cf-turnstile-response" }}
onSuccess={onChangeCaptchaProvider}
onExpire={() => { captcha.current?.reset(); }}
onError={() => setCaptchaConfirmation('The security check encountered an error. Please refresh the page and try again.')}
/>
{captchaConfirmation && (
<div className={styles.error_label}>
{captchaConfirmation}
</div>
)}
</Grid>
<TurnstileCaptcha
captcha={captcha}
className={styles.turnstile}
errorClassName={styles.error_label}
/>
<Grid container item justify='center'>
<Button
variant="contained"
Expand Down Expand Up @@ -198,9 +178,14 @@ const theme = createTheme({
},
});

ReactDOM.render(
<MuiThemeProvider theme={theme}>
<ForgotPasswordPage {...config} />
</MuiThemeProvider>,
document.querySelector("#root")
);
export { ForgotPasswordPage };

const root = document.querySelector("#root");
if (root) {
ReactDOM.render(
<MuiThemeProvider theme={theme}>
<ForgotPasswordPage {...config} />
</MuiThemeProvider>,
root
);
}
Loading
Loading