| @@ -43,8 +43,14 @@ | ||
| 43 | 43 | add_action( 'enqueue_block_editor_assets', [ $self, 'global_css_variable' ] ); |
| 44 | 44 | add_action( 'enqueue_block_editor_assets', [ $self, 'add_editor_inline_css' ] ); |
| 45 | 45 | add_action( 'enqueue_block_editor_assets', [ $self, 'editor_google_fonts' ] ); |
| 46 | 46 | |
| 47 | + // The localized ablocks_nonce is minted once per page load, so a tab left | |
| 48 | + // open past the nonce lifetime (or across a re-login) 403s on every | |
| 49 | + // aBlocks request. Renew it the way core renews wp_rest. | |
| 50 | + add_filter( 'wp_refresh_nonces', [ $self, 'refresh_heartbeat_nonce' ] ); | |
| 51 | + add_action( 'wp_ajax_ablocks/refresh_nonce', [ $self, 'ajax_refresh_nonce' ] ); | |
| 52 | + | |
| 47 | 53 | // Detect page |
| 48 | 54 | add_action( 'wp', array( $self, 'detect_page' ) ); |
| 49 | 55 | |
| 50 | 56 | if ( ! is_admin() && Helper::is_enabled_assets_generation() ) { |
| @@ -157,8 +163,42 @@ | ||
| 157 | 163 | // frontend it would publish the filesystem layout in page source. No |
| 158 | 164 | // frontend script reads it (it is re-exported but never consumed). |
| 159 | 165 | unset( $data['plugin_root_path'] ); |
| 160 | 166 | return $data; |
| 167 | + } | |
| 168 | + | |
| 169 | + /** | |
| 170 | + * Whether the current user is issued ablocks_nonce in the editor or the | |
| 171 | + * dashboard, and so may have it renewed. Mirrors the gates above. | |
| 172 | + */ | |
| 173 | + private function can_renew_nonce() { | |
| 174 | + return is_user_logged_in() && ( current_user_can( 'edit_posts' ) || current_user_can( Permissions::ACCESS ) ); | |
| 175 | + } | |
| 176 | + | |
| 177 | + /** | |
| 178 | + * Heartbeat: hand an open page a fresh ablocks_nonce whenever core refreshes | |
| 179 | + * its own nonces (the page's nonces are ageing, or the session changed). | |
| 180 | + * | |
| 181 | + * @param array $response The Heartbeat response. | |
| 182 | + * @return array | |
| 183 | + */ | |
| 184 | + public function refresh_heartbeat_nonce( $response ) { | |
| 185 | + if ( $this->can_renew_nonce() ) { | |
| 186 | + $response['ablocks_nonce'] = wp_create_nonce( 'ablocks_nonce' ); | |
| 187 | + } | |
| 188 | + return $response; | |
| 189 | + } | |
| 190 | + | |
| 191 | + /** | |
| 192 | + * A fresh ablocks_nonce for a request that was rejected with a stale one — | |
| 193 | + * the aBlocks counterpart of core's `rest-nonce` action. Logged-in only, and | |
| 194 | + * only for users who would be given the nonce on page load anyway. | |
| 195 | + */ | |
| 196 | + public function ajax_refresh_nonce() { | |
| 197 | + if ( ! $this->can_renew_nonce() ) { | |
| 198 | + wp_send_json_error( [ 'message' => 'forbidden' ], 403 ); | |
| 199 | + } | |
| 200 | + wp_send_json_success( [ 'nonce' => wp_create_nonce( 'ablocks_nonce' ) ] ); | |
| 161 | 201 | } |
| 162 | 202 | |
| 163 | 203 | /** |
| 164 | 204 | * Whether the frontend ABlocksGlobal payload has been attached this request. |