From b92e4c28c65aab7d2148dd1317538a0fac50264e Mon Sep 17 00:00:00 2001 From: muli Date: Wed, 3 Aug 2022 18:04:03 +0200 Subject: [PATCH] feat: Switched time based bot protection from JS to PHP sessions. --- assets/js/contact_form.js | 20 +++++++++++++++++--- assets/php/contact_form.php | 31 ++++++++++++++++++++++++------- 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/assets/js/contact_form.js b/assets/js/contact_form.js index c4182dd..87e90e6 100644 --- a/assets/js/contact_form.js +++ b/assets/js/contact_form.js @@ -8,13 +8,27 @@ const captcha = document.getElementsByClassName('contact_form__captcha')[0]; const now = (new Date().getTime()/1000).toFixed(); const feedback = document.getElementsByClassName('contact_form__feedback')[0]; +window.addEventListener('DOMContentLoaded', function(event) { + let formData = new FormData(); + formData.append('action', 'start_session'); + fetch(ajaxUrl, { + method: 'POST', + mode: 'same-origin', + body: formData, + }) + .then(response => response.json()) + .then(json => { + console.log(json); + }) +}); + contact_form.addEventListener('submit', function(event) { event.preventDefault(); let formData = new FormData(); + formData.append('action', 'handle_form'); formData.append('message', message.value); formData.append('name', name.value); formData.append('email', email.value); - formData.append('time_sent', now); // If some bot entered some value, return. if (typeof captcha.value == 'undefined') { @@ -26,12 +40,12 @@ contact_form.addEventListener('submit', function(event) { fetch(ajaxUrl, { method: 'POST', - mode:'same-origin', + mode: 'same-origin', body: formData, }) .then(response => response.json()) .then(json => { - console.log(json) + console.log(json); if (json.errors) { feedback.classList.add('--error'); // Über errors iterieren und diese ausgeben (evtl. nur ersten Fehler ausgeben?) diff --git a/assets/php/contact_form.php b/assets/php/contact_form.php index ebc5b10..205c11b 100644 --- a/assets/php/contact_form.php +++ b/assets/php/contact_form.php @@ -1,7 +1,5 @@ 3600 + time() - $_SESSION['start_time'] < 5 or + time() - $_SESSION['start_time'] > 3600 ) { $response['errors'][] = 'Wir glauben du bist ein Bot.'; } @@ -76,6 +73,26 @@ if ($_SERVER["REQUEST_METHOD"] == "POST") { $response['status'] = 'ok'; } } + return $response; +} + +if ($_SERVER["REQUEST_METHOD"] == "POST") { + $response = array(); + + if (empty($_POST['action'])){ + $response['errors'][] = 'Kann eigentlich nicht passieren :/'; + } else { + if ($_POST['action'] == 'start_session') { + $_SESSION['start_time'] = time(); + // $response['session_start_time'] = $_SESSION['start_time']; + // $response['session_id_before'] = session_id(); + } elseif ($_POST['action'] == 'handle_form') { + $response = prepare_response(); + session_destroy(); + } else { + $response['errors'][] = 'Kann eigentlich auch nicht passieren :/'; + } + } send_response($response); } else { http_response_code(404);