EditAccessMiddleware.php
1 month ago
FullAccessMiddleware.php
1 month ago
VerifyRestNonceMiddleware.php
14 hours ago
ViewAccessMiddleware.php
1 month ago
ViewOrPreviewMiddleware.php
1 month ago
VerifyRestNonceMiddleware.php
53 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Kirki\App\Http\Middlewares; |
| 4 | |
| 5 | defined('ABSPATH') || exit; |
| 6 | |
| 7 | use Kirki\Framework\Contracts\Middleware; |
| 8 | use Kirki\Framework\Contracts\Request; |
| 9 | use Kirki\Framework\Exceptions\AuthorizationException; |
| 10 | use Kirki\Framework\Http\Response; |
| 11 | |
| 12 | /** |
| 13 | * Verifies the WordPress REST nonce (action "wp_rest") for otherwise public |
| 14 | * endpoints such as the front-end form submission route. |
| 15 | * |
| 16 | * The front-end form client sends the nonce in the `X-WP-Nonce` header |
| 17 | * (see builder/src/lib/api.js, populated from `wp_kirki.nonce`, which is |
| 18 | * `wp_create_nonce( 'wp_rest' )`). Requiring a valid nonce ensures a submission |
| 19 | * originates from a genuinely rendered page instead of a blind unauthenticated |
| 20 | * POST, restoring the check that existed in the deprecated FormController. |
| 21 | */ |
| 22 | class VerifyRestNonceMiddleware implements Middleware |
| 23 | { |
| 24 | /** |
| 25 | * Handle the incoming request and reject it when the nonce is missing or invalid. |
| 26 | * |
| 27 | * @param Request $request The incoming request instance. |
| 28 | * @param callable $next The next middleware or controller to execute. |
| 29 | * @return mixed |
| 30 | */ |
| 31 | public function handle(Request $request, callable $next) |
| 32 | { |
| 33 | $nonce = ''; |
| 34 | |
| 35 | if (!empty($_SERVER['HTTP_X_WP_NONCE'])) { |
| 36 | $nonce = sanitize_text_field(wp_unslash($_SERVER['HTTP_X_WP_NONCE'])); |
| 37 | } |
| 38 | |
| 39 | if ($nonce === '') { |
| 40 | $nonce = (string) $request->get_string('_wpnonce', ''); |
| 41 | } |
| 42 | |
| 43 | if ($nonce === '' || !wp_verify_nonce($nonce, 'wp_rest')) { |
| 44 | throw new AuthorizationException( |
| 45 | __('Nonce verification failed', 'kirki'), |
| 46 | Response::FORBIDDEN |
| 47 | ); |
| 48 | } |
| 49 | |
| 50 | return $next($request); |
| 51 | } |
| 52 | } |
| 53 |