| 1 |
<?php |
| 2 |
|
| 3 |
namespace Sendy\WooCommerce\Modules; |
| 4 |
|
| 5 |
use GuzzleHttp\Exception\GuzzleException; |
| 6 |
use Sendy\WooCommerce\ApiClientFactory; |
| 7 |
|
| 8 |
class OAuth |
| 9 |
{ |
| 10 |
public function __construct() |
| 11 |
{ |
| 12 |
add_action('admin_init', [$this, 'initialize_credentials']); |
| 13 |
add_action('admin_init', [$this, 'oauth_callback']); |
| 14 |
} |
| 15 |
|
| 16 |
/** |
| 17 |
* Initialize or reset the OAuth credentials |
| 18 |
* |
| 19 |
* When the client is not yet determined the manager will create a client id and secret pair. When the domain of the |
| 20 |
* site changed, the id/secret pair will be reset because the redirect URI for the OAuth connection will be changed |
| 21 |
* as well. In that case the user will need to re-authenticate with the application. |
| 22 |
* |
| 23 |
* @return void |
| 24 |
*/ |
| 25 |
public function initialize_credentials(): void |
| 26 |
{ |
| 27 |
if (get_option('sendy_client_id') == '' || get_option('sendy_hostname') != get_site_url()) { |
| 28 |
update_option('sendy_client_id', wp_generate_uuid4()); |
| 29 |
update_option('sendy_client_secret', wp_generate_password(40)); |
| 30 |
|
| 31 |
update_option('sendy_access_token', null); |
| 32 |
update_option('sendy_refresh_token', null); |
| 33 |
update_option('sendy_token_expires', null); |
| 34 |
|
| 35 |
update_option('sendy_hostname', get_site_url()); |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
/** |
| 40 |
* Handle the OAuth callback |
| 41 |
* |
| 42 |
* |
| 43 |
* |
| 44 |
* @return void |
| 45 |
*/ |
| 46 |
public function oauth_callback(): void |
| 47 |
{ |
| 48 |
if (isset($_GET['sendy_oauth_callback'])) { |
| 49 |
if (!current_user_can('manage_woocommerce')) { |
| 50 |
wp_die('You do not have sufficient permissions to access this page.'); |
| 51 |
} |
| 52 |
|
| 53 |
if (!isset($_GET['state']) || !wp_verify_nonce(sanitize_key($_GET['state']), 'sendy_oauth_callback_nonce')) { |
| 54 |
wp_die('Nonce verification failed.'); |
| 55 |
} |
| 56 |
|
| 57 |
if (!isset($_GET['code'])) { |
| 58 |
wp_die('Missing code parameter in the URL'); |
| 59 |
} |
| 60 |
|
| 61 |
try { |
| 62 |
$connection = ApiClientFactory::buildConnectionUsingCode(sanitize_key($_GET['code'])); |
| 63 |
|
| 64 |
$connection->checkOrAcquireAccessToken(); |
| 65 |
|
| 66 |
sendy_flash_admin_notice('success', __('Authentication successful', 'sendy')); |
| 67 |
|
| 68 |
wp_safe_redirect(admin_url('admin.php?page=sendy')); |
| 69 |
} catch (GuzzleException $e) { |
| 70 |
sendy_flash_admin_notice('warning', __('Authentication failed. Please try again', 'sendy')); |
| 71 |
|
| 72 |
wp_safe_redirect(admin_url('admin.php?page=sendy')); |
| 73 |
} finally { |
| 74 |
exit; |
| 75 |
} |
| 76 |
} |
| 77 |
} |
| 78 |
} |
| 79 |
|