/
Behavior.php
279 lines (245 loc) · 7.04 KB
/
Behavior.php
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
<?php
declare(strict_types=1);
namespace Wearesho\ReCaptcha\V3\Yii2;
use yii\di;
use yii\web;
use yii\base;
use Wearesho\ReCaptcha;
/**
* Class Behavior
* @package Wearesho\ReCaptcha\V3\Yii2
*/
class Behavior extends base\Behavior
{
public const HEADER = 'X-ReCaptcha-Token';
public const ERROR_MISSING_HEADER = 21001;
public const ERROR_NOT_SUCCESSFUL = 21002;
public const ERROR_TOO_LOW = 21003;
public const ERROR_TOO_HIGH = 21004;
public const ERROR_INVALID_HOSTNAME = 21005;
public const ERROR_INVALID_ACTION = 21006;
/**
* Will be used to check reCAPTCHA token
* @var array|string|ReCaptcha\V3\Client
*/
public $client = [
'class' => ReCaptcha\V3\Client::class,
];
/**
* Will be used to compare environment
* @see environments
* @var array|string|ConfigInterface
*/
public $config = [
'class' => ConfigInterface::class,
];
/**
* Request will be used to fetch reCAPTCHA token from headers
* @var array|string|web\Request
*/
public $request = 'request';
/**
* Header name will be used to fetch reCAPTCHA token
* @var string
*/
public $header = self::HEADER;
/**
* Value between 0 and 1 to compare with google score
* Set to null to skip minimal value checking
* `$this->min > $score` condition will be used
*
* @var int
*/
public $min = null;
/**
* Value between 0 and 1 to compare with google score
* Set to null to skip maximal value checking
* `$score > $this->max` condition will be used
*
* @var int|null
*/
public $max = null;
/**
* If passed hostname from reCAPTCHA response will be compared with all values
* @var string[]|null
*/
public $hostNames = null;
/**
* Controller actions to check. Where key is action id and value is array of method
*
* ```php
* // @var \Wearesho\ReCaptcha\V3\Yii2\Behavior $behavior
* $behavior->actions = [
* 'login' => ['post'],
* 'stats' => ['get', 'post'],
* ]
* ```
* if set to null all actions will be checked
*
* @var string[][]|null
*/
public $actions = null;
/**
* Environments to check.
* If set to null all environments will be checked.
* @see ConfigInterface
* @var null
*/
public $environments = null;
/**
* @throws base\InvalidConfigException
*/
public function init(): void
{
parent::init();
$this->client = di\Instance::ensure($this->client, ReCaptcha\V3\Client::class);
$this->request = di\Instance::ensure($this->request, web\Request::class);
if (!is_null($this->environments)) {
$this->config = di\Instance::ensure($this->config, ConfigInterface::class);
}
}
public function events(): array
{
return [
base\Controller::EVENT_BEFORE_ACTION => 'beforeAction',
];
}
/**
* @param base\ActionEvent $event
*
* @throws web\HttpException
*
*/
public function beforeAction(base\ActionEvent $event): void
{
if (!$this->matchEnvironment()) {
return;
}
if (!is_null($this->actions)) {
$actionMatches = array_key_exists($event->action->id, $this->actions ?? []);
if (!$actionMatches) {
return;
}
$methodMatches = in_array(strtolower($this->request->method), $this->actions[$event->action->id]);
if (!$methodMatches) {
return;
}
}
$token = $this->request->headers->get($this->header);
if (is_null($token)) {
$this->challengeFailed();
return;
}
try {
$response = $this->client->verify($token, $this->request->userIP);
} catch (ReCaptcha\V3\Exception $e) {
$this->notSuccessful($e);
return;
}
if (!is_null($this->min) && $this->min > $response->getScore()) {
$this->tooLow($response);
return;
}
if (!is_null($this->max) && $response->getScore() > $this->max) {
$this->tooHigh($response);
return;
}
if (!is_null($this->hostNames) && !in_array($response->getHostname(), $this->hostNames)) {
$this->invalidHostName($response);
return;
}
$needleCaptchaAction = preg_replace('/[^\w]/', '', mb_strtolower(
"{$event->action->controller->id}{$event->action->id}{$this->request->method}"
));
if ($needleCaptchaAction !== $response->getAction()) {
$this->invalidAction($response);
return;
}
}
protected function matchEnvironment(): bool
{
if (is_null($this->environments)) {
return true;
}
$currentEnvironment = $this->config->getEnvironment();
foreach ($this->environments as $environment) {
if ($environment === $currentEnvironment) {
return true;
}
}
return false;
}
/**
* @throws web\HttpException
*/
protected function challengeFailed(): void
{
throw new web\BadRequestHttpException(
"reCAPTCHA challenge failed",
static::ERROR_MISSING_HEADER
);
}
/**
* @param ReCaptcha\V3\Exception $exception
*
* @throws web\HttpException
*/
protected function notSuccessful(ReCaptcha\V3\Exception $exception): void
{
throw new web\BadRequestHttpException(
"reCAPTCHA challenge failed",
static::ERROR_NOT_SUCCESSFUL,
$exception
);
}
/**
* @param ReCaptcha\V3\Response $response @
*
* @throws web\HttpException
*/
protected function tooLow(ReCaptcha\V3\Response $response): void
{
$this->validationError($response, static::ERROR_TOO_LOW);
}
/**
* @param ReCaptcha\V3\Response $response @
*
* @throws web\HttpException
*/
protected function tooHigh(ReCaptcha\V3\Response $response): void
{
$this->validationError($response, static::ERROR_TOO_HIGH);
}
/**
* @param ReCaptcha\V3\Response $response @
*
* @throws web\HttpException
*/
protected function invalidHostName(ReCaptcha\V3\Response $response): void
{
$this->validationError($response, static::ERROR_INVALID_HOSTNAME);
}
/**
* @param ReCaptcha\V3\Response $response @
*
* @throws web\HttpException
*/
protected function invalidAction(ReCaptcha\V3\Response $response): void
{
$this->validationError($response, static::ERROR_INVALID_ACTION);
}
/**
* @param ReCaptcha\V3\Response $response
* @param int $code
*
* @throws web\HttpException
*
*/
protected function validationError(ReCaptcha\V3\Response $response, int $code): void
{
throw new web\BadRequestHttpException(
"reCAPTCHA challenge failed",
$code
);
}
}