| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Metricool\Http\Middleware; |
| 6 |
|
| 7 |
use Metricool\Interfaces\MiddlewareInterface; |
| 8 |
use Metricool\Traits\HasNonces; |
| 9 |
use Metricool\Traits\HasRestAccess; |
| 10 |
|
| 11 |
/** |
| 12 |
* Verify the nonce for incoming REST API requests. For methods that modify data (POST, PUT, PATCH, DELETE), the request must include a valid nonce in the 'nonce' parameter. |
| 13 |
*/ |
| 14 |
class VerifyNonce implements MiddlewareInterface |
| 15 |
{ |
| 16 |
use HasRestAccess; |
| 17 |
use HasNonces; |
| 18 |
|
| 19 |
public function handle(\WP_REST_Request $request, callable $next) |
| 20 |
{ |
| 21 |
$method = $request->get_method(); |
| 22 |
$nonce = $request->get_param('nonce'); |
| 23 |
|
| 24 |
// For methods that modify data, verify the nonce |
| 25 |
$methodsRequiringNonce = ['POST', 'PUT', 'PATCH', 'DELETE']; |
| 26 |
if (in_array($method, $methodsRequiringNonce) && ($this->verifyNonce($nonce) === false)) { |
| 27 |
return $this->sendHttpErrorResponse( |
| 28 |
'Forbidden', |
| 29 |
null, |
| 30 |
403 |
| 31 |
); |
| 32 |
} |
| 33 |
|
| 34 |
return $next($request); |
| 35 |
} |
| 36 |
} |
| 37 |
|