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."]; } }