diff --git a/public/index.php b/public/index.php index 4d566f3..87108e6 100644 --- a/public/index.php +++ b/public/index.php @@ -1,6 +1,7 @@ delete('/api/feeds/{id}', [ApiController::class, 'deleteFeed']); $app->get('/api/categories', [ApiController::class, 'getCategories']); $app->get('/api/tags', [ApiController::class, 'getTags']); +// Маршруты для владельцев (агентов) +$app->post('/api/owners/register', [OwnerController::class, 'registerOwner']); +$app->get('/api/owners/me', [OwnerController::class, 'getOwnerByApiKey']); + // Маршрут для главной страницы $app->get('/', function (Request $request, Response $response) { $response->getBody()->write(file_get_contents(__DIR__ . '/../templates/index.html')); diff --git a/src/Controllers/OwnerController.php b/src/Controllers/OwnerController.php new file mode 100644 index 0000000..c917a4d --- /dev/null +++ b/src/Controllers/OwnerController.php @@ -0,0 +1,121 @@ +db = $db; + } + + /** + * Регистрация нового владельца (агента) + */ + public function registerOwner(Request $request, Response $response): Response + { + try { + $data = $request->getParsedBody(); + + // Валидация данных + if (empty($data['name'])) { + $response->getBody()->write(json_encode(['error' => 'Имя владельца обязательно'])); + return $response->withStatus(400)->withHeader('Content-Type', 'application/json'); + } + + // Проверить, что владелец с таким именем не существует + $checkStmt = $this->db->prepare("SELECT id FROM owners WHERE name = :name"); + $checkStmt->execute([':name' => $data['name']]); + if ($checkStmt->fetch()) { + $response->getBody()->write(json_encode(['error' => 'Владелец с таким именем уже существует'])); + return $response->withStatus(409)->withHeader('Content-Type', 'application/json'); + } + + // Генерация уникального API ключа + $apiKey = bin2hex(random_bytes(32)); // 64-символьный hex API ключ + + // Регистрация владельца + $sql = "INSERT INTO owners (name, contact, api_key, status) VALUES (:name, :contact, :api_key, :status)"; + $stmt = $this->db->prepare($sql); + $result = $stmt->execute([ + ':name' => $data['name'], + ':contact' => $data['contact'] ?? '', + ':api_key' => $apiKey, + ':status' => 'active' + ]); + + if ($result) { + $ownerId = $this->db->lastInsertId(); + + // Вернуть информацию о зарегистрированном владельце без чувствительных данных + $resultData = [ + 'id' => $ownerId, + 'name' => $data['name'], + 'api_key' => $apiKey, // Только что сгенерированный API ключ для этого владельца + 'registered_at' => date('Y-m-d H:i:s') + ]; + + $response->getBody()->write(json_encode($resultData)); + return $response->withHeader('Content-Type', 'application/json'); + } else { + $response->getBody()->write(json_encode(['error' => 'Не удалось зарегистрировать владельца'])); + return $response->withStatus(500)->withHeader('Content-Type', 'application/json'); + } + } catch (\Exception $e) { + $response->getBody()->write(json_encode(['error' => $e->getMessage()])); + return $response->withStatus(500)->withHeader('Content-Type', 'application/json'); + } + } + + /** + * Получить информацию о владельце по API ключу + */ + public function getOwnerByApiKey(Request $request, Response $response): Response + { + try { + $apiKey = $request->getHeaderLine('X-API-Key') ?: ($request->getQueryParams()['api_key'] ?? ''); + + if (empty($apiKey)) { + $response->getBody()->write(json_encode(['error' => 'API ключ обязателен'])); + return $response->withStatus(401)->withHeader('Content-Type', 'application/json'); + } + + $sql = "SELECT id, name, contact, created_at, last_activity FROM owners WHERE api_key = :api_key AND status = 'active'"; + $stmt = $this->db->prepare($sql); + $stmt->execute([':api_key' => $apiKey]); + $owner = $stmt->fetch(); + + if ($owner) { + $response->getBody()->write(json_encode($owner)); + return $response->withHeader('Content-Type', 'application/json'); + } else { + $response->getBody()->write(json_encode(['error' => 'Владелец не найден или неактивен'])); + return $response->withStatus(404)->withHeader('Content-Type', 'application/json'); + } + } catch (\Exception $e) { + $response->getBody()->write(json_encode(['error' => $e->getMessage()])); + return $response->withStatus(500)->withHeader('Content-Type', 'application/json'); + } + } + + /** + * Обновить последнюю активность владельца + */ + public function updateOwnerActivity(string $apiKey): void + { + try { + $stmt = $this->db->prepare("UPDATE owners SET last_activity = NOW() WHERE api_key = :api_key"); + $stmt->execute([':api_key' => $apiKey]); + } catch (\Exception $e) { + // Просто логируем ошибку, не прерываем основной процесс + error_log("Error updating owner activity: " . $e->getMessage()); + } + } +} \ No newline at end of file