| 1 |
<?php |
| 2 |
namespace BBlocks\Inc; |
| 3 |
class BBlocksApiKeys{ |
| 4 |
function __construct(){ |
| 5 |
add_action( 'wp_ajax_bblocks_api_keys', [$this, 'bBlocksApiKeys'] ); |
| 6 |
// nopriv hook intentionally omitted — this action requires manage_options capability. |
| 7 |
} |
| 8 |
|
| 9 |
function bBlocksTestApiKeys($key,$value){ |
| 10 |
if ($key == 'openAi') { |
| 11 |
return BBlocksAi::get_instance()->test_api_key($value); |
| 12 |
} |
| 13 |
if ($key == 'instagram') { |
| 14 |
return BBlocksInstagram::test_token($value); |
| 15 |
} |
| 16 |
} |
| 17 |
|
| 18 |
function bBlocksApiKeys(){ |
| 19 |
$nonce = sanitize_text_field( wp_unslash( $_POST['_wpnonce']?? null ) ) ; |
| 20 |
|
| 21 |
if( !wp_verify_nonce( $nonce, 'wp_ajax' ) ){ |
| 22 |
wp_send_json_error( ['message'=>'Invalid Request'] ); |
| 23 |
} |
| 24 |
|
| 25 |
if (!current_user_can('manage_options')) { |
| 26 |
wp_send_json_error( ['message'=>'Unauthorized'] ); |
| 27 |
} |
| 28 |
|
| 29 |
$key = sanitize_text_field(wp_unslash($_POST['key'] ?? '')); |
| 30 |
$value = sanitize_text_field(wp_unslash($_POST['value'] ?? '')); |
| 31 |
$apiKeys = get_option('bBlocksApiKeys',[]); |
| 32 |
$error = $this->bBlocksTestApiKeys($key,$value); |
| 33 |
|
| 34 |
if (isset($error['valid']) && !$error['valid']) { |
| 35 |
wp_send_json_error([$key=>$error]); |
| 36 |
} |
| 37 |
if ($key) { |
| 38 |
$apiKeys[$key] = ['key'=> $value]; |
| 39 |
update_option( 'bBlocksApiKeys',$apiKeys); |
| 40 |
} |
| 41 |
wp_send_json_success($apiKeys); |
| 42 |
} |
| 43 |
} |
| 44 |
new BBlocksApiKeys(); |