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
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ NEXT_PUBLIC_MATOMO_URL="https://choiceof.dev/matomo/"
NEXT_PUBLIC_MATOMO_SITE_ID="1"
NEXT_PUBLIC_SLUG_FOR_OFFICIAL_PREVIEW="pizza-or-instant-noodles"
NEXT_PUBLIC_API_URL="http://localhost:1234/api.php"
NEXT_PUBLIC_CLOUDFLARE_TURNSTILE_SITE_KEY="0x4AAAAAAABX6tUdT3sWYN82"
13 changes: 13 additions & 0 deletions apps/devchoices-next/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import init from '@socialgouv/matomo-next'
const MATOMO_URL = process.env.NEXT_PUBLIC_MATOMO_URL
const MATOMO_SITE_ID = process.env.NEXT_PUBLIC_MATOMO_SITE_ID
const WEBSITE_URL = process.env.NEXT_PUBLIC_WEBSITE_URL
const TURNSTILE_SITE_KEY = process.env.NEXT_PUBLIC_CLOUDFLARE_TURNSTILE_SITE_KEY

export const QuestionContext = createContext<{
questions: QuestionInterface[]
Expand Down Expand Up @@ -98,6 +99,18 @@ function CustomApp({ Component, pageProps, router }: AppProps) {
<Component {...pageProps} key={url} />
</AnimatePresence>

<div id="turnstile-widget"></div>
<Script src="https://challenges.cloudflare.com/turnstile/v0/api.js" onLoad={() => {
window.turnstileWidgetId = turnstile.render('#turnstile-widget', {
sitekey: TURNSTILE_SITE_KEY,
callback: function (token) {
window.turnstileToken = token
},
});
window.refreshTurnstileToken = function () {
turnstile.reset(window.turnstileWidgetId)
}
}}></Script>
<Script id="matomo" strategy="lazyOnload">
{`
var _paq = window._paq = window._paq || [];
Expand Down
22 changes: 11 additions & 11 deletions apps/devchoices-next/pages/question/[slug].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,30 +92,30 @@ export function QuestionPage(props: QuestionPageProps) {
await router.push('/question/' + questionContext.questions[questionContext.questions.indexOf(question) + 1].slug)
}

const onLeft = () => {
// todo store the +1 in the database
const postPosition = (p: Number) => {
const form = new FormData()
form.append('position', '0')
form.append('position', p.toString())
form.append('token', window.turnstileToken)
fetch(`${process.env.NEXT_PUBLIC_API_URL}?slug=${slug}`, {
method: 'POST',
body: form,
}).catch(() => {
setVoteValues([voteValues[0], voteValues[1] + 1])
}).finally(() => {
window.refreshTurnstileToken()
})
}

const onLeft = () => {
// todo store the +1 in the database
postPosition(0)
setVoteValues([voteValues[0] + 1, voteValues[1]])
setShowResult(true)
}

const onRight = () => {
// todo store the +1 in the database
const form = new FormData()
form.append('position', '1')
fetch(`${process.env.NEXT_PUBLIC_API_URL}?slug=${slug}`, {
method: 'POST',
body: form,
}).catch(() => {
setVoteValues([voteValues[0], voteValues[1] + 1])
})
postPosition(1)
setVoteValues([voteValues[0], voteValues[1] + 1])
setShowResult(true)
}
Expand Down
21 changes: 19 additions & 2 deletions php/api.php
Original file line number Diff line number Diff line change
@@ -1,13 +1,30 @@
<?php
require_once '../../config.php';
require_once 'turnstile.php';

if (isset($_SERVER['HTTP_ORIGIN']))
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Methods: GET, POST');

include('../../config.php');
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
$token = $_POST['token'] ?? null;
if (is_null($token)) {
http_response_code(400);
echo 'no-token';
return;
}

$validationResult = validateToken($token, $config['CLOUDFLARE_TURNSTILE_SECRET']);
if (is_null($validationResult) || $validationResult['success'] !== true) {
http_response_code(400);
echo 'invalid-token';
return;
}
}

$pdo = new PDO("mysql:dbname=" . $config['DB_NAME'] . ";host=" . $config['DB_HOST'], $config['DB_USER'], $config['DB_PASSWORD']);
$method = $_SERVER['REQUEST_METHOD'];
$slug = $_GET['slug'] ?? null;
$dispatchCountOn = 50;
$ip = $_SERVER["REMOTE_ADDR"];
Expand Down
21 changes: 21 additions & 0 deletions php/turnstile.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php
function validateToken($token, $secretKey)
{
$stream = stream_context_create([
'http' => [
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query(['secret' => $secretKey, 'response' => $token])]
]);

$result = file_get_contents(
'https://challenges.cloudflare.com/turnstile/v0/siteverify',
false,
$stream);

if ($result === false) {
return null;
}

return json_decode($result, true);
}