85 lines
2.7 KiB
PHP
85 lines
2.7 KiB
PHP
<?php
|
|
require_once __DIR__ . '/config.php';
|
|
|
|
/**
|
|
* Generate a new API key, hash it, store it, and return the plain text key.
|
|
*
|
|
* @param string $keyName User-defined name for the key.
|
|
* @param string $integrationType The type of integration (e.g., 'n8n', 'callrail').
|
|
* @return array Result array with success status, plain text API key, and key name.
|
|
*/
|
|
function generateApiKey($keyName, $integrationType) {
|
|
if (empty($keyName) || empty($integrationType)) {
|
|
return ["success" => false, "message" => "Key name and integration type are required."];
|
|
}
|
|
|
|
$plainKey = bin2hex(random_bytes(16));
|
|
$hashedKey = password_hash($plainKey, PASSWORD_DEFAULT);
|
|
|
|
$pdo = db();
|
|
$stmt = $pdo->prepare(
|
|
"INSERT INTO api_keys (key_name, api_key_hash, integration_type, is_active, rate_limit_per_minute, created_at)
|
|
VALUES (:key_name, :api_key_hash, :integration_type, true, 60, NOW())"
|
|
);
|
|
|
|
$stmt->bindParam(':key_name', $keyName);
|
|
$stmt->bindParam(':api_key_hash', $hashedKey);
|
|
$stmt->bindParam(':integration_type', $integrationType);
|
|
|
|
if ($stmt->execute()) {
|
|
return ["success" => true, "api_key" => $plainKey, "key_name" => $keyName, "id" => $pdo->lastInsertId()];
|
|
} else {
|
|
return ["success" => false, "message" => "Failed to generate API key."];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* List all API keys from the database (excluding the hash).
|
|
*
|
|
* @return array An array of API key records.
|
|
*/
|
|
function listApiKeys() {
|
|
$pdo = db();
|
|
$stmt = $pdo->query(
|
|
"SELECT id, key_name, integration_type, is_active, last_used_at, created_at, expires_at
|
|
FROM api_keys ORDER BY created_at DESC"
|
|
);
|
|
return $stmt->fetchAll(PDO::FETCH_ASSOC);
|
|
}
|
|
|
|
/**
|
|
* Deactivate an API key.
|
|
*
|
|
* @param int $keyId The ID of the key to deactivate.
|
|
* @return array Result array with success status and a message.
|
|
*/
|
|
function deactivateApiKey($keyId) {
|
|
$pdo = db();
|
|
$stmt = $pdo->prepare("UPDATE api_keys SET is_active = false WHERE id = :id");
|
|
$stmt->bindParam(':id', $keyId, PDO::PARAM_INT);
|
|
|
|
if ($stmt->execute()) {
|
|
return ["success" => true, "message" => "API key deactivated."];
|
|
} else {
|
|
return ["success" => false, "message" => "Failed to deactivate API key."];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Delete an API key.
|
|
*
|
|
* @param int $keyId The ID of the key to delete.
|
|
* @return array Result array with success status and a message.
|
|
*/
|
|
function deleteApiKey($keyId) {
|
|
$pdo = db();
|
|
$stmt = $pdo->prepare("DELETE FROM api_keys WHERE id = :id");
|
|
$stmt->bindParam(':id', $keyId, PDO::PARAM_INT);
|
|
|
|
if ($stmt->execute()) {
|
|
return ["success" => true, "message" => "API key deleted."];
|
|
} else {
|
|
return ["success" => false, "message" => "Failed to delete API key."];
|
|
}
|
|
}
|