From 705c70a72e0dfce3b2feb182bf121282fb56a32e Mon Sep 17 00:00:00 2001
From: Grzegorz Rola <grola@seostudio.pl>
Date: Fri, 3 Mar 2023 11:50:15 +0100
Subject: [PATCH] feature(ajax): added nonce

---
 src/WPDesk/Notice/AjaxHandler.php                 |  5 ++++-
 .../tests/integration/AjaxHandlerTest.php         | 15 ++++++++++++++-
 2 files changed, 18 insertions(+), 2 deletions(-)

diff --git a/src/WPDesk/Notice/AjaxHandler.php b/src/WPDesk/Notice/AjaxHandler.php
index be5311e..263e84b 100644
--- a/src/WPDesk/Notice/AjaxHandler.php
+++ b/src/WPDesk/Notice/AjaxHandler.php
@@ -94,10 +94,13 @@ class AjaxHandler implements HookablePluginDependant {
                     PermanentDismissibleNotice::OPTION_VALUE_DISMISSED
                 );
                 do_action( 'wpdesk_notice_dismissed_notice', $noticeName, $source );
+                if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
+                    wp_send_json_success();
+                }
             }
         }
         if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
-            die();
+            wp_send_json_error();
         }
     }
 
diff --git a/tests/codeception/tests/integration/AjaxHandlerTest.php b/tests/codeception/tests/integration/AjaxHandlerTest.php
index 13f1572..c0f40f9 100644
--- a/tests/codeception/tests/integration/AjaxHandlerTest.php
+++ b/tests/codeception/tests/integration/AjaxHandlerTest.php
@@ -81,7 +81,7 @@ class AjaxHandlerTest extends WPTestCase {
 		$_POST[ AjaxHandler::POST_FIELD_NOTICE_NAME ] = self::NOTICE_NAME;
         $_POST[ AjaxHandler::POST_FIELD_SECURITY ] = wp_create_nonce( PermanentDismissibleNotice::OPTION_NAME_PREFIX . sanitize_text_field( self::NOTICE_NAME ) );
 
-		$ajaxHandler = new AjaxHandler( self::ASSETS_URL );
+        $ajaxHandler = new AjaxHandler( self::ASSETS_URL );
 		$ajaxHandler->processAjaxNoticeDismiss();
 
 		$this->assertEquals(
@@ -90,4 +90,17 @@ class AjaxHandlerTest extends WPTestCase {
 		);
 	}
 
+    public function testShoulfNotProcessAjaxNoticeDismissWhenInvalidNonce() {
+        $_POST[ AjaxHandler::POST_FIELD_NOTICE_NAME ] = self::NOTICE_NAME;
+        $_POST[ AjaxHandler::POST_FIELD_SECURITY ] = wp_create_nonce();
+
+        $ajaxHandler = new AjaxHandler( self::ASSETS_URL );
+        $ajaxHandler->processAjaxNoticeDismiss();
+
+        $this->assertNotEquals(
+            PermanentDismissibleNotice::OPTION_VALUE_DISMISSED,
+            get_option( PermanentDismissibleNotice::OPTION_NAME_PREFIX . self::NOTICE_NAME )
+        );
+    }
+
 }
-- 
GitLab