csrf-token-model.php
3 years ago
csrf-token-view.php
3 years ago
csrf-tools.php
3 years ago
wp-nonce-tools.php
3 years ago
wp-nonce-tools.php
67 lines
| 1 | <?php |
| 2 | |
| 3 | |
| 4 | namespace Jet_Form_Builder\Classes\Security; |
| 5 | |
| 6 | use Jet_Form_Builder\Exceptions\Request_Exception; |
| 7 | |
| 8 | class Wp_Nonce_Tools { |
| 9 | |
| 10 | const KEY = '_wpnonce'; |
| 11 | |
| 12 | public static function register() { |
| 13 | add_filter( |
| 14 | 'jet-form-builder/request-handler/request', |
| 15 | array( static::class, 'handle_request' ) |
| 16 | ); |
| 17 | add_filter( |
| 18 | 'jet-form-builder/message-types', |
| 19 | array( static::class, 'handle_messages' ) |
| 20 | ); |
| 21 | } |
| 22 | |
| 23 | public static function get_nonce_id(): string { |
| 24 | $form_id = jet_fb_live_args()->form_id; |
| 25 | |
| 26 | return "jet-form-builder-wp-nonce-{$form_id}"; |
| 27 | } |
| 28 | |
| 29 | public static function get_nonce_field(): string { |
| 30 | if ( ! jet_fb_live_args()->is_use_nonce() ) { |
| 31 | return ''; |
| 32 | } |
| 33 | |
| 34 | return wp_nonce_field( static::get_nonce_id(), self::KEY, true, false ); |
| 35 | } |
| 36 | |
| 37 | public static function verify( $nonce ): bool { |
| 38 | return ( ! jet_fb_live_args()->is_use_nonce() || wp_verify_nonce( $nonce, static::get_nonce_id() ) ); |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * @param array $request |
| 43 | * |
| 44 | * @return array |
| 45 | * @throws Request_Exception |
| 46 | */ |
| 47 | public static function handle_request( array $request ): array { |
| 48 | $nonce = $request[ self::KEY ] ?? ''; |
| 49 | |
| 50 | if ( ! self::verify( $nonce ) ) { |
| 51 | throw new Request_Exception( 'nonce_failed' ); |
| 52 | } |
| 53 | |
| 54 | return $request; |
| 55 | } |
| 56 | |
| 57 | public static function handle_messages( array $messages ): array { |
| 58 | $messages['nonce_failed'] = array( |
| 59 | 'label' => __( 'WP nonce validation failed', 'jet-form-builder' ), |
| 60 | 'value' => __( 'Invalid nonce', 'jet-form-builder' ), |
| 61 | ); |
| 62 | |
| 63 | return $messages; |
| 64 | } |
| 65 | |
| 66 | } |
| 67 |