feat: Admin API key REST controller
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace AskTamMCP\Admin;
|
||||
|
||||
defined('ABSPATH') || exit;
|
||||
|
||||
/**
|
||||
* REST routes for API key CRUD (used by admin dashboard JS).
|
||||
* Admin-only, requires WP cookie auth or application password.
|
||||
*/
|
||||
class ApiKeyController {
|
||||
|
||||
public function registerRoutes(): void {
|
||||
register_rest_route('asktam-mcp/v1', '/keys', [
|
||||
['methods' => 'GET', 'callback' => [$this, 'listKeys'], 'permission_callback' => [$this, 'adminCap']],
|
||||
['methods' => 'POST', 'callback' => [$this, 'createKey'], 'permission_callback' => [$this, 'adminCap']],
|
||||
]);
|
||||
|
||||
register_rest_route('asktam-mcp/v1', '/keys/(?P<id>\d+)', [
|
||||
['methods' => 'DELETE', 'callback' => [$this, 'revokeKey'], 'permission_callback' => [$this, 'adminCap']],
|
||||
]);
|
||||
}
|
||||
|
||||
public function adminCap(): bool {
|
||||
return current_user_can('manage_options');
|
||||
}
|
||||
|
||||
public function listKeys(\WP_REST_Request $request): \WP_REST_Response {
|
||||
global $wpdb;
|
||||
$table = $wpdb->prefix . 'asktam_mcp_keys';
|
||||
$rows = $wpdb->get_results("SELECT id, name, scopes, created_at, last_used, is_active FROM {$table} ORDER BY created_at DESC", ARRAY_A);
|
||||
return new \WP_REST_Response($rows);
|
||||
}
|
||||
|
||||
public function createKey(\WP_REST_Request $request): \WP_REST_Response {
|
||||
global $wpdb;
|
||||
$table = $wpdb->prefix . 'asktam_mcp_keys';
|
||||
$name = sanitize_text_field($request->get_param('name'));
|
||||
$scopes = $request->get_param('scopes') ?? ['read'];
|
||||
|
||||
if (empty($name)) {
|
||||
return new \WP_REST_Response(['error' => 'Name is required'], 400);
|
||||
}
|
||||
|
||||
$rawKey = \AskTamMCP\Core\Auth::generateKey();
|
||||
$scopes = implode(',', array_map('sanitize_text_field', (array) $scopes));
|
||||
|
||||
$wpdb->insert($table, ['name' => $name, 'api_key' => $rawKey, 'scopes' => $scopes, 'created_at' => current_time('mysql'), 'is_active' => 1]);
|
||||
|
||||
return new \WP_REST_Response(['id' => $wpdb->insert_id, 'name' => $name, 'api_key' => $rawKey, 'scopes' => $scopes], 201);
|
||||
}
|
||||
|
||||
public function revokeKey(\WP_REST_Request $request): \WP_REST_Response {
|
||||
global $wpdb;
|
||||
$table = $wpdb->prefix . 'asktam_mcp_keys';
|
||||
$id = (int) $request->get_param('id');
|
||||
$wpdb->update($table, ['is_active' => 0], ['id' => $id]);
|
||||
return new \WP_REST_Response(['id' => $id, 'revoked' => true]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user