55 lines
1.7 KiB
PHP
55 lines
1.7 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Modules\ApiKeys;
|
|
|
|
use App\Core\{Request, Response, Database};
|
|
use Ramsey\Uuid\Uuid;
|
|
|
|
final class ApiKeyController
|
|
{
|
|
public function list(Request $request): void
|
|
{
|
|
$tenantId = $request->tenantId;
|
|
$db = Database::getInstance();
|
|
$stmt = $db->prepare("SELECT id, name, public_key, created_at, last_used_at, is_active FROM api_keys WHERE tenant_id = ? ORDER BY created_at DESC");
|
|
$stmt->execute([$tenantId]);
|
|
|
|
Response::json([
|
|
'success' => true,
|
|
'data' => $stmt->fetchAll()
|
|
]);
|
|
}
|
|
|
|
public function create(Request $request): void
|
|
{
|
|
$tenantId = $request->tenantId;
|
|
$userId = $request->user->user_id;
|
|
$name = $request->input('name');
|
|
|
|
if (!$name) {
|
|
Response::error('يرجى إدخال اسم المفتاح', 'VALIDATION_ERROR', 422);
|
|
return;
|
|
}
|
|
|
|
$id = Uuid::uuid4()->toString();
|
|
$publicKey = bin2hex(random_bytes(16));
|
|
$secretKey = bin2hex(random_bytes(32));
|
|
$secretHash = password_hash($secretKey, PASSWORD_BCRYPT);
|
|
|
|
$db = Database::getInstance();
|
|
$stmt = $db->prepare("INSERT INTO api_keys (id, tenant_id, user_id, name, public_key, secret_hash, is_active) VALUES (?, ?, ?, ?, ?, ?, 1)");
|
|
$stmt->execute([$id, $tenantId, $userId, $name, $publicKey, $secretHash]);
|
|
|
|
Response::json([
|
|
'success' => true,
|
|
'message' => 'تم إنشاء مفتاح API بنجاح. يرجى حفظ السر لأنه لن يظهر مرة أخرى.',
|
|
'data' => [
|
|
'id' => $id,
|
|
'key' => "msq_{$publicKey}.{$secretKey}"
|
|
]
|
|
], 201);
|
|
}
|
|
}
|