🚀 مُصادَق: تحديث برمجي جديد 2026-05-03 14:27
This commit is contained in:
@@ -4,56 +4,50 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\ApiKeys;
|
||||
|
||||
use App\Core\{Request, Response};
|
||||
use App\Modules\ApiKeys\ApiKeyModel;
|
||||
use App\Core\{Request, Response, Database};
|
||||
use Ramsey\Uuid\Uuid;
|
||||
|
||||
final class ApiKeyController
|
||||
{
|
||||
public function __construct(private readonly ApiKeyModel $apiKeyModel) {}
|
||||
|
||||
public function list(Request $request): void
|
||||
{
|
||||
$tenantId = $request->tenantId;
|
||||
$keys = $this->apiKeyModel->findAllByTenant($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' => $keys
|
||||
'data' => $stmt->fetchAll()
|
||||
]);
|
||||
}
|
||||
|
||||
public function create(Request $request): void
|
||||
{
|
||||
$tenantId = $request->tenantId;
|
||||
$data = $request->getBody();
|
||||
$userId = $request->user->user_id;
|
||||
$name = $request->input('name');
|
||||
|
||||
if (empty($data['name'])) {
|
||||
Response::error('اسم المفتاح مطلوب', 'VALIDATION_ERROR', 422);
|
||||
if (!$name) {
|
||||
Response::error('يرجى إدخال اسم المفتاح', 'VALIDATION_ERROR', 422);
|
||||
return;
|
||||
}
|
||||
|
||||
$id = \Ramsey\Uuid\Uuid::uuid4()->toString();
|
||||
// Generate a random key
|
||||
$rawKey = bin2hex(random_bytes(32));
|
||||
$prefix = substr($rawKey, 0, 8);
|
||||
$hashedKey = hash('sha256', $rawKey);
|
||||
$id = Uuid::uuid4()->toString();
|
||||
$publicKey = bin2hex(random_bytes(16));
|
||||
$secretKey = bin2hex(random_bytes(32));
|
||||
$secretHash = password_hash($secretKey, PASSWORD_BCRYPT);
|
||||
|
||||
$this->apiKeyModel->create([
|
||||
'id' => $id,
|
||||
'tenant_id' => $tenantId,
|
||||
'name' => $data['name'],
|
||||
'key_hash' => $hashedKey,
|
||||
'prefix' => $prefix,
|
||||
'is_active' => 1
|
||||
]);
|
||||
$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 بنجاح',
|
||||
'message' => 'تم إنشاء مفتاح API بنجاح. يرجى حفظ السر لأنه لن يظهر مرة أخرى.',
|
||||
'data' => [
|
||||
'id' => $id,
|
||||
'name' => $data['name'],
|
||||
'key' => $rawKey // Only shown once!
|
||||
'key' => "msq_{$publicKey}.{$secretKey}"
|
||||
]
|
||||
], 201);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user