Add owner registration system for agents with API key generation

This commit is contained in:
Vladimir Mirivlad 2026-02-06 04:29:25 +00:00
parent f383d611ae
commit 8393182b48
2 changed files with 126 additions and 0 deletions

View File

@ -1,6 +1,7 @@
<?php
use App\Controllers\ApiController;
use App\Controllers\OwnerController;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
@ -48,6 +49,10 @@ $app->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'));

View File

@ -0,0 +1,121 @@
<?php
namespace App\Controllers;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use PDO;
use Ramsey\Uuid\Uuid;
class OwnerController
{
private $db;
public function __construct(PDO $db)
{
$this->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());
}
}
}