| 1 |
<?php |
| 2 |
|
| 3 |
namespace ImageOptimization\Modules\Connect\Rest; |
| 4 |
|
| 5 |
use ImageOptimization\Modules\Connect\Classes\{ |
| 6 |
Data, |
| 7 |
Route_Base, |
| 8 |
Service, |
| 9 |
Utils |
| 10 |
}; |
| 11 |
|
| 12 |
use ImageOptimization\Modules\Connect\Module as Connect; |
| 13 |
use Throwable; |
| 14 |
use WP_REST_Request; |
| 15 |
|
| 16 |
if ( ! defined( 'ABSPATH' ) ) { |
| 17 |
exit; // Exit if accessed directly |
| 18 |
} |
| 19 |
|
| 20 |
/** |
| 21 |
* Class Authorize |
| 22 |
*/ |
| 23 |
class Authorize extends Route_Base { |
| 24 |
public string $path = 'authorize'; |
| 25 |
public const NONCE_NAME = 'wp_rest'; |
| 26 |
|
| 27 |
public function get_methods(): array { |
| 28 |
return [ 'POST' ]; |
| 29 |
} |
| 30 |
|
| 31 |
public function get_name(): string { |
| 32 |
return 'authorize'; |
| 33 |
} |
| 34 |
|
| 35 |
public function POST( WP_REST_Request $request ) { |
| 36 |
$this->verify_nonce_and_capability( |
| 37 |
$request->get_param( self::NONCE_NAME ), |
| 38 |
self::NONCE_NAME |
| 39 |
); |
| 40 |
|
| 41 |
if ( Connect::is_connected() ) { |
| 42 |
return $this->respond_error_json( [ |
| 43 |
'message' => esc_html__( 'You are already connected', 'image-optimization' ), |
| 44 |
'code' => 'forbidden', |
| 45 |
] ); |
| 46 |
} |
| 47 |
|
| 48 |
try { |
| 49 |
$client_id = Data::get_client_id(); |
| 50 |
|
| 51 |
if ( ! $client_id ) { |
| 52 |
$client_id = Service::register_client(); |
| 53 |
} |
| 54 |
|
| 55 |
$authorize_url = Utils::get_authorize_url( $client_id ); |
| 56 |
|
| 57 |
return $this->respond_success_json( $authorize_url ); |
| 58 |
} catch ( Throwable $t ) { |
| 59 |
return $this->respond_error_json( [ |
| 60 |
'message' => $t->getMessage(), |
| 61 |
'code' => 'internal_server_error', |
| 62 |
] ); |
| 63 |
} |
| 64 |
} |
| 65 |
} |
| 66 |
|