| 1 |
<?php |
| 2 |
|
| 3 |
namespace ImageOptimization\Modules\Connect\Components; |
| 4 |
|
| 5 |
use ImageOptimization\Modules\Connect\Classes\{ |
| 6 |
Config, |
| 7 |
Data, |
| 8 |
GrantTypes, |
| 9 |
Service, |
| 10 |
Utils, |
| 11 |
}; |
| 12 |
use ImageOptimization\Classes\Services\Client; |
| 13 |
|
| 14 |
if ( ! defined( 'ABSPATH' ) ) { |
| 15 |
exit; // Exit if accessed directly |
| 16 |
} |
| 17 |
|
| 18 |
/** |
| 19 |
* Class Handler |
| 20 |
*/ |
| 21 |
class Handler { |
| 22 |
private function should_handle_auth_code(): bool { |
| 23 |
global $plugin_page; |
| 24 |
|
| 25 |
$page_slug = explode( 'page=', Config::ADMIN_PAGE ); |
| 26 |
|
| 27 |
$is_connect_admin_page = false; |
| 28 |
|
| 29 |
if ( ! empty( $page_slug[1] ) && $page_slug[1] === $plugin_page ) { |
| 30 |
$is_connect_admin_page = true; |
| 31 |
} |
| 32 |
|
| 33 |
if ( ! $is_connect_admin_page && Config::ADMIN_PAGE === $plugin_page ) { |
| 34 |
$is_connect_admin_page = true; |
| 35 |
} |
| 36 |
|
| 37 |
if ( ! $is_connect_admin_page ) { |
| 38 |
return false; |
| 39 |
} |
| 40 |
|
| 41 |
$code = $_GET['code'] ?? null; |
| 42 |
$state = $_GET['state'] ?? null; |
| 43 |
|
| 44 |
if ( empty( $code ) || empty( $state ) ) { |
| 45 |
return false; |
| 46 |
} |
| 47 |
|
| 48 |
return true; |
| 49 |
} |
| 50 |
|
| 51 |
private function validate_nonce( $state ) { |
| 52 |
if ( ! wp_verify_nonce( $state, Config::STATE_NONCE ) ) { |
| 53 |
wp_die( 'Invalid state' ); |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
public function handle_auth_code() { |
| 58 |
if ( ! $this->should_handle_auth_code() ) { |
| 59 |
return; |
| 60 |
} |
| 61 |
|
| 62 |
$code = sanitize_text_field( $_GET['code'] ); |
| 63 |
$state = sanitize_text_field( $_GET['state'] ); |
| 64 |
|
| 65 |
// Check if the state is valid |
| 66 |
$this->validate_nonce( $state ); |
| 67 |
|
| 68 |
// Exchange the code for an access token and store it |
| 69 |
Service::get_token( GrantTypes::AUTHORIZATION_CODE, $code ); |
| 70 |
|
| 71 |
// Makes sure we won't stick in the mismatch limbo |
| 72 |
Data::set_home_url(); |
| 73 |
|
| 74 |
// Redirect to the redirect URI |
| 75 |
wp_redirect( Utils::get_redirect_uri() ); |
| 76 |
exit; |
| 77 |
} |
| 78 |
|
| 79 |
/** |
| 80 |
* Handler constructor. |
| 81 |
*/ |
| 82 |
public function __construct() { |
| 83 |
add_action( 'admin_init', [ $this, 'handle_auth_code' ] ); |
| 84 |
} |
| 85 |
} |
| 86 |
|