-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathturnstile_protect.module
60 lines (50 loc) · 1.77 KB
/
turnstile_protect.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
/**
* @file
* Primary module hooks for Turnstile Protect module.
*/
/**
* Implements hook_captcha_alter().
*/
function turnstile_protect_captcha_alter(&$captcha, $info) {
if ($info['module'] !== 'turnstile') {
return;
}
if (\Drupal::routeMatch()->getRouteName() !== 'turnstile_protect.challenge') {
return;
}
// Block referrer to cloudflare.
$captcha['form']['turnstile_widget']['#attached']['html_head'][0][0]['#attributes']['referrerpolicy'] = 'no-referrer';
// Add a javascript callback after the turnstile succeeds.
$captcha['form']['turnstile_widget']['#markup'] = str_replace('<div', '<div data-callback="turnstileProtectAutoSubmit"', $captcha['form']['turnstile_widget']['#markup']);
$captcha['form']['#attached']['library'][] = 'turnstile_protect/challenge';
}
/**
* Implements hook_cron().
*/
function turnstile_protect_cron() {
$config = \Drupal::config('turnstile_protect.settings');
if (!$config->get('history_enabled')) {
return;
}
$window = $config->get('window');
$current_time = \Drupal::time()->getRequestTime();
$threshold_timestamp = $current_time - $window;
// Add a 15m buffer.
$threshold_timestamp -= 900;
// Retrieve the last execution time.
$result = \Drupal::database()->query("SELECT MAX(timestamp) FROM {turnstile_protect_history}")->fetchField();
// Run only if there's no recent execution.
if ($result && $result >= $threshold_timestamp) {
return;
}
\Drupal::database()->query("INSERT INTO {turnstile_protect_history} (`timestamp`, ip_range, requests)
SELECT :current_time, identifier, COUNT(*)
FROM {flood}
WHERE `event` = :event
GROUP BY identifier
ORDER BY COUNT(*) DESC", [
':event' => 'turnstile_protect_rate_limit',
':current_time' => $current_time,
]);
}