Skip to content

Commit

Permalink
remove recaptcha (#1103)
Browse files Browse the repository at this point in the history
  • Loading branch information
sspenst authored May 18, 2024
1 parent 4b41c8d commit 3a48c82
Show file tree
Hide file tree
Showing 9 changed files with 13 additions and 237 deletions.
39 changes: 2 additions & 37 deletions components/forms/signupForm.tsx
Original file line number Diff line number Diff line change
@@ -1,33 +1,19 @@
import Link from 'next/link';
import { useRouter } from 'next/router';
import React, { useContext, useRef, useState } from 'react';
import ReCAPTCHA from 'react-google-recaptcha';
import React, { useContext, useState } from 'react';
import toast from 'react-hot-toast';
import { useSWRConfig } from 'swr';
import { AppContext } from '../../contexts/appContext';
import FormTemplate from './formTemplate';

interface SignupFormProps {
recaptchaPublicKey?: string;
}

export default function SignupForm({ recaptchaPublicKey }: SignupFormProps) {
export default function SignupForm() {
const { cache } = useSWRConfig();
const [email, setEmail] = useState<string>('');
const { mutateUser, setShouldAttemptAuth } = useContext(AppContext);
const [password, setPassword] = useState<string>('');
const recaptchaRef = useRef<ReCAPTCHA>(null);
const [recaptchaToken, setRecaptchaToken] = useState<string>('');
const router = useRouter();
const [showRecaptcha, setShowRecaptcha] = useState<boolean>(false);
const [username, setUsername] = useState<string>('');

function onRecaptchaChange(value: string | null) {
if (value) {
setRecaptchaToken(value);
}
}

function onSubmit(event: React.FormEvent) {
event.preventDefault();

Expand All @@ -52,12 +38,6 @@ export default function SignupForm({ recaptchaPublicKey }: SignupFormProps) {
return;
}

if (!showRecaptcha && recaptchaPublicKey) {
setShowRecaptcha(true);

return;
}

toast.dismiss();
toast.loading('Registering...');

Expand All @@ -71,18 +51,13 @@ export default function SignupForm({ recaptchaPublicKey }: SignupFormProps) {
name: username,
password: password,
tutorialCompletedAt: parseInt(tutorialCompletedAt),
recaptchaToken: recaptchaToken,
utm_source: utm_source
}),
credentials: 'include',
headers: {
'Content-Type': 'application/json'
}
}).then(async res => {
if (recaptchaRef.current) {
recaptchaRef.current.reset();
}

if (res.status === 200) {
const resObj = await res.json();

Expand Down Expand Up @@ -136,16 +111,6 @@ export default function SignupForm({ recaptchaPublicKey }: SignupFormProps) {
</label>
<input onChange={e => setPassword(e.target.value)} className='shadow appearance-none border rounded w-full py-2 px-3 leading-tight focus:outline-none focus:shadow-outline' id='password' type='password' placeholder='******************' />
</div>
{recaptchaPublicKey && showRecaptcha && (
<div className='w-full pt-2'>
<ReCAPTCHA
size='normal'
onChange={onRecaptchaChange}
ref={recaptchaRef}
sitekey={recaptchaPublicKey ?? ''}
/>
</div>
)}
<div className='flex items-center justify-between gap-1'>
<input type='checkbox' id='terms_agree_checkbox' required />
<label htmlFor='terms_agree_checkbox' className='text-xs p-1'>
Expand Down
35 changes: 0 additions & 35 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@
"react-dnd": "^16.0.1",
"react-dnd-html5-backend": "^16.0.1",
"react-dom": "^18.3.1",
"react-google-recaptcha": "^3.1.0",
"react-gtm-module": "^2.0.11",
"react-hot-toast": "^2.4.1",
"react-joyride": "^2.8.1",
Expand Down Expand Up @@ -112,7 +111,6 @@
"@types/nprogress": "^0.2.3",
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.0",
"@types/react-google-recaptcha": "^2.1.9",
"@types/react-gtm-module": "^2.0.3",
"@types/recharts": "^1.8.29",
"@types/request-ip": "^0.0.41",
Expand Down
51 changes: 6 additions & 45 deletions pages/[subdomain]/play-as-guest/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,34 +5,23 @@ import redirectToHome from '@root/helpers/redirectToHome';
import { GetServerSidePropsContext } from 'next';
import Link from 'next/link';
import { useRouter } from 'next/router';
import React, { useContext, useRef, useState } from 'react';
import ReCAPTCHA from 'react-google-recaptcha';
import React, { useContext, useState } from 'react';
import { toast } from 'react-hot-toast';
import { useSWRConfig } from 'swr';

export async function getServerSideProps(context: GetServerSidePropsContext) {
return await redirectToHome(context, { recaptchaPublicKey: process.env.RECAPTCHA_PUBLIC_KEY || '' });
return await redirectToHome(context);
}

/* istanbul ignore next */
export default function PlayAsGuest({ recaptchaPublicKey }: {recaptchaPublicKey?: string}) {
export default function PlayAsGuest() {
const { cache } = useSWRConfig();
const { userConfig, mutateUser, setShouldAttemptAuth } = useContext(AppContext);
const [name, setName] = useState<string>('');
const recaptchaRef = useRef<ReCAPTCHA>(null);
const recaptchaToken = useRef('');
const [registrationState, setRegistrationState] = useState('registering');
const router = useRouter();
const [showRecaptcha, setShowRecaptcha] = useState(false);
const [temporaryPassword, setTemporaryPassword] = useState<string>('');

function onRecaptchaChange(value: string | null) {
if (value) {
recaptchaToken.current = value;
setTimeout(fetchSignup, 50);
}
}

const CopyToClipboardButton = ({ text }: { text: string }) => {
const [isCopied, setIsCopied] = useState(false);

Expand Down Expand Up @@ -125,38 +114,15 @@ export default function PlayAsGuest({ recaptchaPublicKey }: {recaptchaPublicKey?
<li>Your guest account may be deleted after 7 days of no activity</li>
<li>By creating a guest account you agree to our <a className='underline' href='https://docs.google.com/document/d/e/2PACX-1vR4E-RcuIpXSrRtR3T3y9begevVF_yq7idcWWx1A-I9w_VRcHhPTkW1A7DeUx2pGOcyuKifEad3Qokn/pub' rel='noreferrer' target='_blank'>terms of service</a> and reviewed the <a className='underline' href='https://docs.google.com/document/d/e/2PACX-1vSNgV3NVKlsgSOEsnUltswQgE8atWe1WCLUY5fQUVjEdu_JZcVlRkZcpbTOewwe3oBNa4l7IJlOnUIB/pub' rel='noreferrer' target='_blank'>privacy policy</a></li>
</ul>
{recaptchaPublicKey && showRecaptcha ?
<ReCAPTCHA
size='normal'
onChange={onRecaptchaChange}
ref={recaptchaRef}
sitekey={recaptchaPublicKey ?? ''}
/>
:
<button className='bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline cursor-pointer' onClick={fetchSignup}>
Play
</button>
}
<button className='bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline cursor-pointer' onClick={fetchSignup}>
Play
</button>
<Link className='font-bold text-sm text-blue-500 hover:text-blue-400' href='/signup'>
Sign up with a regular account instead
</Link>
</div>;

async function fetchSignup() {
if (recaptchaPublicKey) {
if (!showRecaptcha) {
setShowRecaptcha(true);

return;
}

if (!recaptchaToken.current) {
toast.error('Please complete the recaptcha');

return;
}
}

const tutorialCompletedAt = window.localStorage.getItem('tutorialCompletedAt') || '0';
const utm_source = window.localStorage.getItem('utm_source') || '';

Expand All @@ -173,17 +139,12 @@ export default function PlayAsGuest({ recaptchaPublicKey }: {recaptchaPublicKey?
name: 'Guest',
email: 'guest@guest.com',
password: 'guest-account',
recaptchaToken: recaptchaToken.current,
guest: true,
tutorialCompletedAt: tutorialCompletedAt,
utm_source: utm_source
})
});

if (recaptchaRef.current) {
recaptchaRef.current.reset();
}

if (!res.ok) {
toast.dismiss();
toast.error('Error creating guest account');
Expand Down
16 changes: 3 additions & 13 deletions pages/[subdomain]/signup/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,11 @@ import Page from '../../../components/page/page';
import redirectToHome from '../../../helpers/redirectToHome';

export async function getServerSideProps(context: GetServerSidePropsContext) {
const redirect = await redirectToHome(context);

if (redirect.redirect) {
return redirect;
}

return {
props: {
recaptchaPublicKey: process.env.RECAPTCHA_PUBLIC_KEY || '',
},
};
return await redirectToHome(context);
}

/* istanbul ignore next */
export default function SignUp({ recaptchaPublicKey }: {recaptchaPublicKey?: string}) {
export default function SignUp() {
return (
<Page title={'Sign Up'}>
<>
Expand All @@ -34,7 +24,7 @@ export default function SignUp({ recaptchaPublicKey }: {recaptchaPublicKey?: str
<div>Create a Thinky.gg account and start playing!</div><div>Your Thinky.gg account works across all games on the site.</div>
</div>
</div>
<SignupForm recaptchaPublicKey={recaptchaPublicKey} />
<SignupForm />
<div className='text-center mb-4'>
{'Already have an account? '}
<Link href='/login' passHref className='underline'>
Expand Down
29 changes: 2 additions & 27 deletions pages/api/signup/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,38 +68,13 @@ export default apiWrapper({ POST: {
email: ValidType('string'),
name: ValidType('string'),
password: ValidType('string'),
recaptchaToken: ValidType('string', false),
tutorialCompletedAt: ValidNumber(false),
utm_source: ValidType('string', false),
},
} }, async (req: NextApiRequestWrapper, res: NextApiResponse) => {
await dbConnect();

const { email, name, password, tutorialCompletedAt, recaptchaToken, guest, utm_source } = req.body;

const RECAPTCHA_SECRET = process.env.RECAPTCHA_SECRET || '';

if (RECAPTCHA_SECRET && RECAPTCHA_SECRET.length > 0) {
if (!recaptchaToken) {
return res.status(400).json({ error: 'Please fill out recaptcha' });
}

const recaptchaResponse = await fetch('https://www.google.com/recaptcha/api/siteverify', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `secret=${RECAPTCHA_SECRET}&response=${recaptchaToken}`,
});

const recaptchaData = await recaptchaResponse.json();

if (!recaptchaResponse.ok || !recaptchaData?.success) {
const errorMessage = `Error validating recaptcha [Status: ${recaptchaResponse.status}], [Data: ${JSON.stringify(recaptchaData)}]`;

logger.error(errorMessage);

return res.status(400).json({ error: errorMessage });
}
}

const { guest, email, name, password, tutorialCompletedAt, utm_source } = req.body;
let trimmedEmail: string, trimmedName: string, passwordValue: string;

if (guest) {
Expand Down
Loading

0 comments on commit 3a48c82

Please sign in to comment.