Раздел «Вебхуки» в панели, команды webhook:list и webhook:test

Подписки на события видны и правятся из панели: события галочками, секрет
с заменой, пробная посылка, журнал доставок со страницами. Состояние
показывает число подписок и недоставленных посылок.
This commit is contained in:
rsgrinko committed 2026-09-13 00:29:57 +03:00
1 parent fce276bb13
commit 054c1f2897
11 files changed
+825 -2

No files matched your search

@@ -0,0 +1,209 @@
<?php
declare(strict_types=1);
namespace App\Controllers\Admin;
use Rsgrinko\Proton\Http\Controller;
use Rsgrinko\Proton\Http\Request;
use Rsgrinko\Proton\Http\Response;
use Rsgrinko\Proton\Models\Webhook;
use Rsgrinko\Proton\Models\WebhookDelivery;
use Rsgrinko\Proton\Support\Audit;
use Rsgrinko\Proton\View\View;
use Rsgrinko\Proton\Webhooks\Webhooks;
/**
* Подписки на события: куда стучаться, о чём и с каким секретом.
*
* Секрет виден владельцу подписки всегда — им подписчик проверяет посылки,
* и подсмотреть его больше негде. Заменить секрет можно, и старый перестаёт
* подходить сразу.
*/
final class WebhooksController extends Controller
{
public function index(Request $request): Response
{
return $this->view('admin/webhooks', [
'active' => 'webhooks',
'page' => Webhook::query()->orderBy('id', 'desc')->paginate($this->page($request), $this->perPage()),
'groups' => Webhooks::groups(),
'stats' => WebhookDelivery::stats(),
], 'Вебхуки');
}
public function create(): Response
{
return $this->view('admin/webhook', [
'active' => 'webhooks',
'webhook' => new Webhook(),
'groups' => Webhooks::groups(),
'deliveries' => ['items' => [], 'total' => 0, 'page' => 1, 'pages' => 1, 'per_page' => 0],
'fresh' => '',
], 'Новая подписка');
}
public function store(Request $request): Response
{
$data = $this->validate($request, [
'name' => 'nullable|max:191',
'url' => 'required|url|max:500',
'secret' => 'nullable|max:191',
], ['name' => 'Название', 'url' => 'Адрес', 'secret' => 'Секрет']);
$events = Webhooks::filter((array) $request->input('events', []));
if ($events === []) {
$this->flash('Выберите хотя бы одно событие', 'error');
return $this->redirect('admin.webhooks.create');
}
$webhook = Webhook::add(
(string) ($data['name'] ?? ''),
(string) $data['url'],
$events,
(string) ($data['secret'] ?? '')
);
Audit::created('webhook', $webhook->id(), 'подписка «' . (string) $webhook->name . '» на ' . (string) $webhook->url);
$this->flash('Подписка создана. Секрет пропишите у подписчика');
return $this->redirect('admin.webhooks.show', ['id' => $webhook->id()]);
}
public function show(Request $request, int $id): Response
{
$webhook = $this->webhook($id);
return $this->view('admin/webhook', [
'active' => 'webhooks',
'webhook' => $webhook,
'groups' => Webhooks::groups(),
'deliveries' => WebhookDelivery::query()
->where('webhook_id', $webhook->id())
->orderBy('id', 'desc')
->paginate($this->page($request), $this->perPage()),
// Новый секрет показываем один раз, сразу после замены
'fresh' => (string) View::takeStash('webhook_secret', ''),
], (string) $webhook->name);
}
public function update(Request $request, int $id): Response
{
$webhook = $this->webhook($id);
$data = $this->validate($request, [
'name' => 'nullable|max:191',
'url' => 'required|url|max:500',
], ['name' => 'Название', 'url' => 'Адрес']);
$events = Webhooks::filter((array) $request->input('events', []));
if ($events === []) {
$this->flash('Выберите хотя бы одно событие', 'error');
return $this->redirect('admin.webhooks.show', ['id' => $webhook->id()]);
}
$before = [
'name' => (string) $webhook->name,
'url' => (string) $webhook->url,
'events' => implode(', ', $webhook->events()),
];
$webhook->forceFill([
'name' => (string) ($data['name'] ?? '') !== '' ? (string) $data['name'] : (string) $webhook->name,
'url' => (string) $data['url'],
'events' => json_encode($events, JSON_UNESCAPED_UNICODE),
])->save();
Audit::updated('webhook', $webhook->id(), 'подписка «' . (string) $webhook->name . '»', Audit::between($before, [
'name' => (string) $webhook->name,
'url' => (string) $webhook->url,
'events' => implode(', ', $webhook->events()),
]));
$this->flash('Подписка сохранена');
return $this->redirect('admin.webhooks.show', ['id' => $webhook->id()]);
}
/**
* Включить или отключить подписку.
*/
public function toggle(int $id): Response
{
$webhook = $this->webhook($id);
$active = !(bool) $webhook->active;
// Включили заново — счётчик неудач больше не повод отключать
$webhook->forceFill(['active' => $active ? 1 : 0, 'failures' => 0])->save();
Audit::action('webhook', $webhook->id(), ($active ? 'включена' : 'отключена') . ' подписка «' . (string) $webhook->name . '»');
$this->flash($active ? 'Подписка включена' : 'Подписка отключена');
return $this->redirect('admin.webhooks.show', ['id' => $webhook->id()]);
}
/**
* Заменить секрет: старый перестаёт подходить сразу.
*/
public function rotate(int $id): Response
{
$webhook = $this->webhook($id);
View::stash('webhook_secret', $webhook->rotateSecret());
Audit::action('webhook', $webhook->id(), 'заменён секрет подписки «' . (string) $webhook->name . '»');
$this->flash('Секрет заменён. Пропишите новый у подписчика — старый больше не подойдёт');
return $this->redirect('admin.webhooks.show', ['id' => $webhook->id()]);
}
/**
* Пробная посылка: уходит очередью, как и настоящие.
*/
public function test(int $id): Response
{
$webhook = $this->webhook($id);
$delivery = Webhooks::test($webhook);
Audit::action('webhook', $webhook->id(), 'отправлена пробная посылка подписке «' . (string) $webhook->name . '»');
$this->flash('Пробная посылка поставлена в очередь (№' . $delivery->id() . '). Её разберёт воркер');
return $this->redirect('admin.webhooks.show', ['id' => $webhook->id()]);
}
public function delete(int $id): Response
{
$webhook = $this->webhook($id);
$name = (string) $webhook->name;
// Журнал доставок без подписки не нужен
WebhookDelivery::query()->where('webhook_id', $webhook->id())->delete();
$webhook->delete();
Audit::deleted('webhook', $id, 'удалена подписка «' . $name . '»');
$this->flash('Подписка удалена');
return $this->redirect('admin.webhooks');
}
private function webhook(int $id): Webhook
{
/** @var Webhook $webhook */
$webhook = $this->require(Webhook::find($id), 'admin.webhooks', 'Подписка не найдена');
return $webhook;
}
}
+1
View File
@@ -20,6 +20,7 @@ return [
['key' => 'users', 'label' => 'Пользователи', 'route' => 'admin.users', 'permission' => Permission::USERS_MANAGE],
['key' => 'roles', 'label' => 'Роли', 'route' => 'admin.roles', 'permission' => Permission::ROLES_MANAGE],
['key' => 'tokens', 'label' => 'Ключи API', 'route' => 'admin.tokens', 'permission' => Permission::USERS_MANAGE],
['key' => 'webhooks', 'label' => 'Вебхуки', 'route' => 'admin.webhooks', 'permission' => Permission::WEBHOOKS_MANAGE],
['key' => 'audit', 'label' => 'Журнал', 'route' => 'admin.audit', 'permission' => Permission::AUDIT_VIEW],
['key' => 'logs', 'label' => 'Логи', 'route' => 'admin.logs', 'permission' => Permission::LOGS_VIEW],
['key' => 'system', 'label' => 'Состояние', 'route' => 'admin.system', 'permission' => Permission::SYSTEM_VIEW],
+4
View File
@@ -66,6 +66,10 @@ final class Application
'Почта' => [
Commands\MailTestCommand::class,
],
'Вебхуки' => [
Commands\WebhookListCommand::class,
Commands\WebhookTestCommand::class,
],
];
/** @var array<int, string> Позиционные аргументы */
@@ -0,0 +1,94 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Models\Webhook;
use Rsgrinko\Proton\Models\WebhookDelivery;
use Rsgrinko\Proton\Webhooks\Webhooks;
/**
* список подписок на события.
*/
final class WebhookListCommand extends Command
{
public function name(): string
{
return 'webhook:list';
}
public function description(): string
{
return 'список подписок на события и состояние посылок';
}
public function usage(): string
{
return 'webhook:list [--events]';
}
public function run(): int
{
if ($this->hasOption('events')) {
return $this->printEvents();
}
/** @var array<int, Webhook> $webhooks */
$webhooks = Webhook::query()->orderBy('id')->get();
if ($webhooks === []) {
$this->line('Подписок нет. Завести: раздел «Вебхуки» в панели');
return 0;
}
$rows = [];
foreach ($webhooks as $webhook) {
$events = $webhook->events();
$rows[] = [
(string) $webhook->id(),
(string) $webhook->name,
(string) $webhook->url,
in_array(Webhook::ALL_EVENTS, $events, true) ? 'все' : (string) count($events),
(bool) $webhook->active ? 'да' : 'нет',
(int) $webhook->raw('last_status') > 0 ? (string) (int) $webhook->raw('last_status') : '—',
(string) ($webhook->raw('last_sent_at') ?? '—'),
];
}
$this->table(['id', 'Название', 'Адрес', 'События', 'Включена', 'Ответ', 'Последняя посылка'], $rows);
$stats = WebhookDelivery::stats();
$this->line();
$this->line(
'Посылки: доставлено ' . (int) ($stats[WebhookDelivery::SENT] ?? 0)
. ', в очереди ' . (int) ($stats[WebhookDelivery::PENDING] ?? 0)
. ', не доставлено ' . (int) ($stats[WebhookDelivery::FAILED] ?? 0)
);
return 0;
}
/**
* Реестр событий: на что вообще можно подписаться.
*/
private function printEvents(): int
{
$rows = [];
foreach (Webhooks::groups() as $group => $events) {
foreach ($events as $code => $label) {
$rows[] = [$group, $code, $label];
}
}
$this->table(['Раздел', 'Событие', 'Что случилось'], $rows);
return 0;
}
}
@@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
namespace Rsgrinko\Proton\Console\Commands;
use Rsgrinko\Proton\Console\Command;
use Rsgrinko\Proton\Models\Webhook;
use Rsgrinko\Proton\Models\WebhookDelivery;
use Rsgrinko\Proton\Webhooks\DeliverWebhookJob;
use Rsgrinko\Proton\Webhooks\Webhooks;
use Throwable;
/**
* пробная посылка подписчику.
*/
final class WebhookTestCommand extends Command
{
public function name(): string
{
return 'webhook:test';
}
public function description(): string
{
return 'отправить подписке пробную посылку';
}
public function usage(): string
{
return 'webhook:test <id> [--queue]';
}
public function run(): int
{
$id = (int) $this->arg(0);
if ($id <= 0) {
$this->fail('Укажите номер подписки: webhook:test 1 (список — webhook:list)');
return 1;
}
$webhook = Webhook::find($id);
if ($webhook === null) {
$this->fail('Подписка ' . $id . ' не найдена');
return 1;
}
$delivery = Webhooks::test($webhook);
// По умолчанию отправляем сразу: ждать воркера, чтобы проверить адрес,
// — лишний шаг. С --queue посылка остаётся в очереди
if ($this->hasOption('queue')) {
$this->ok('Посылка №' . $delivery->id() . ' поставлена в очередь «' . Webhooks::queue() . '»');
return 0;
}
try {
(new DeliverWebhookJob())->handle(['delivery_id' => $delivery->id()]);
} catch (Throwable) {
// Ошибку задача уже записала в журнал доставок — печатаем её ниже,
// вместе с остальным по посылке
}
$delivery = WebhookDelivery::find($delivery->id());
if ($delivery === null) {
return 1;
}
$this->line('Посылка: №' . $delivery->id());
$this->line('Адрес: ' . (string) $webhook->url);
$this->line('Ответ: ' . ((int) $delivery->raw('response_status') > 0 ? (string) (int) $delivery->raw('response_status') : '—'));
$this->line('Время: ' . (int) $delivery->raw('duration_ms') . ' мс');
if ((string) $delivery->raw('status') !== WebhookDelivery::SENT) {
$this->fail('Состояние: ' . $delivery->label() . ' — ' . (string) $delivery->raw('error'));
return 1;
}
$this->ok('Доставлена');
return 0;
}
}
+2 -1
View File
@@ -94,7 +94,8 @@ final class Webhook extends Model
*/
public function events(): array
{
$events = $this->events;
// Читаем raw, а не через приведение: у новой подписки колонки ещё нет
$events = json_decode((string) $this->raw('events'), true);
return is_array($events) ? array_map(static fn (mixed $event): string => (string) $event, $events) : [];
}
+31
View File
@@ -10,6 +10,8 @@ use Rsgrinko\Proton\Database\Migrator;
use Rsgrinko\Proton\Files\Storage;
use Rsgrinko\Proton\Models\Setting;
use Rsgrinko\Proton\Models\User;
use Rsgrinko\Proton\Models\Webhook;
use Rsgrinko\Proton\Models\WebhookDelivery;
use Rsgrinko\Proton\Queue\Queue;
use Throwable;
@@ -247,9 +249,38 @@ final class Diagnostics
'hint' => '',
];
$checks[] = self::webhooks();
return $checks;
}
/**
* Подписки на события: сколько их и нет ли недоставленных посылок.
*
* @return array{level: string, title: string, value: string, hint: string}
*/
private static function webhooks(): array
{
try {
if (!Connection::instance()->hasTable('webhooks')) {
return ['level' => self::OK, 'title' => 'Вебхуки', 'value' => 'таблиц нет', 'hint' => ''];
}
$active = Webhook::query()->where('active', 1)->count();
$failed = (int) (WebhookDelivery::stats()[WebhookDelivery::FAILED] ?? 0);
return self::check(
$failed === 0,
'Вебхуки',
'подписок ' . $active . ', не доставлено ' . $failed,
'Посмотрите журнал доставок: кто-то из подписчиков не отвечает',
self::WARN
);
} catch (Throwable $e) {
return ['level' => self::WARN, 'title' => 'Вебхуки', 'value' => $e->getMessage(), 'hint' => ''];
}
}
/**
* @return array{level: string, title: string, value: string, hint: string}
*/
+199
View File
@@ -0,0 +1,199 @@
<?php
declare(strict_types=1);
/**
* Карточка подписки: адрес, события, секрет и журнал посылок.
*
* @var \Rsgrinko\Proton\Models\Webhook $webhook
* @var array<string, array<string, string>> $groups события по разделам
* @var array{items: array<int, \Rsgrinko\Proton\Models\WebhookDelivery>, total: int, page: int, pages: int, per_page: int} $deliveries
* @var string $fresh только что выданный секрет — показывается один раз
*/
use Rsgrinko\Proton\Models\Webhook;
use Rsgrinko\Proton\Models\WebhookDelivery;
use Rsgrinko\Proton\View\View;
$isNew = !$webhook->existsInDatabase();
$action = $isNew ? View::route('admin.webhooks.create') : View::route('admin.webhooks.show', ['id' => $webhook->id()]);
$selected = $webhook->events();
$all = in_array(Webhook::ALL_EVENTS, $selected, true);
?>
<h1><?= $isNew ? 'Новая подписка' : View::e((string) $webhook->name) ?></h1>
<?php if ($fresh !== '') { ?>
<div class="card" style="border-color: var(--accent);">
<h2>Новый секрет</h2>
<p class="muted small">Пропишите его у подписчика: старый больше не подойдёт.</p>
<pre class="break"><?= View::e($fresh) ?></pre>
<p><?= View::copy($fresh, 'скопировать секрет') ?></p>
</div>
<?php } ?>
<div class="card">
<form method="post" action="<?= View::e($action) ?>">
<?= View::csrf() ?>
<label>
<span>Название</span>
<input type="text" name="name" value="<?= View::e((string) $webhook->name) ?>" placeholder="склад 1С" <?= $isNew ? 'autofocus' : '' ?>>
</label>
<label>
<span>Адрес подписчика</span>
<input type="url" name="url" value="<?= View::e((string) $webhook->url) ?>" placeholder="https://example.com/hooks/proton" required>
</label>
<?php if ($isNew) { ?>
<label>
<span>Секрет подписи (пусто — придумаем сами)</span>
<input type="text" name="secret" value="" autocomplete="off">
</label>
<?php } ?>
<h2 style="margin-top: 16px;">События</h2>
<label class="inline" style="margin-bottom: 6px;">
<input type="checkbox" name="events[]" value="<?= View::e(Webhook::ALL_EVENTS) ?>" <?= $all ? 'checked' : '' ?>>
<span>Все события — в том числе те, что появятся позже</span>
</label>
<?php foreach ($groups as $title => $events) { ?>
<div class="card">
<h2><?= View::e($title) ?></h2>
<?php foreach ($events as $code => $label) { ?>
<label class="inline" style="margin-bottom: 6px;">
<input type="checkbox" name="events[]" value="<?= View::e($code) ?>"
<?= in_array($code, $selected, true) ? 'checked' : '' ?>>
<span><?= View::e($label) ?> <span class="muted mono"><?= View::e($code) ?></span></span>
</label>
<?php } ?>
</div>
<?php } ?>
<div class="row">
<button type="submit" class="primary">Сохранить</button>
<a class="btn" href="<?= View::e(View::route('admin.webhooks')) ?>">К списку</a>
</div>
</form>
</div>
<?php if (!$isNew) { ?>
<div class="card">
<h2>Секрет и состояние</h2>
<table class="list">
<tr>
<th>Секрет</th>
<td class="mono"><?= View::e($webhook->maskedSecret()) ?></td>
</tr>
<tr>
<th>Состояние</th>
<td>
<?php if ((bool) $webhook->active) { ?>
<span class="badge ok">включена</span>
<?php } else { ?>
<span class="badge muted">отключена</span>
<?php } ?>
</td>
</tr>
<tr>
<th>Последняя посылка</th>
<td class="muted small">
<?= View::e(View::ago((string) $webhook->raw('last_sent_at'))) ?>
<?php if ((int) $webhook->raw('last_status') > 0) { ?>
<span class="mono">ответ <?= (int) $webhook->raw('last_status') ?></span>
<?php } ?>
</td>
</tr>
<?php if ((string) $webhook->raw('last_error') !== '') { ?>
<tr>
<th>Последняя ошибка</th>
<td class="small break"><?= View::e((string) $webhook->raw('last_error')) ?></td>
</tr>
<?php } ?>
<tr>
<th>Неудач подряд</th>
<td><?= (int) $webhook->raw('failures') ?></td>
</tr>
</table>
<div class="row" style="margin-top: 12px;">
<form method="post" action="<?= View::e(View::route('admin.webhooks.test', ['id' => $webhook->id()])) ?>">
<?= View::csrf() ?>
<button type="submit" class="primary">Отправить пробную посылку</button>
</form>
<form method="post" action="<?= View::e(View::route('admin.webhooks.toggle', ['id' => $webhook->id()])) ?>">
<?= View::csrf() ?>
<button type="submit"><?= (bool) $webhook->active ? 'Отключить' : 'Включить' ?></button>
</form>
<form method="post" action="<?= View::e(View::route('admin.webhooks.rotate', ['id' => $webhook->id()])) ?>">
<?= View::csrf() ?>
<button type="submit">Заменить секрет</button>
</form>
<form method="post" action="<?= View::e(View::route('admin.webhooks.delete', ['id' => $webhook->id()])) ?>">
<?= View::csrf() ?>
<button type="submit" class="danger">Удалить подписку</button>
</form>
</div>
</div>
<div class="card">
<h2>Посылки</h2>
<?php if ($deliveries['items'] === []) { ?>
<p class="muted">Посылок пока не было.</p>
<?php } else { ?>
<div class="table-wrap">
<table class="list">
<tr class="head">
<th>№</th>
<th>Событие</th>
<th>Состояние</th>
<th class="hide-sm">Ответ</th>
<th class="hide-sm">Попыток</th>
<th class="hide-sm">Время</th>
<th>Когда</th>
</tr>
<?php foreach ($deliveries['items'] as $delivery) { ?>
<tr>
<td class="mono"><?= $delivery->id() ?></td>
<td class="mono small"><?= View::e((string) $delivery->raw('event')) ?></td>
<td>
<?php if ((string) $delivery->raw('status') === WebhookDelivery::SENT) { ?>
<span class="badge ok"><?= View::e($delivery->label()) ?></span>
<?php } elseif ((string) $delivery->raw('status') === WebhookDelivery::FAILED) { ?>
<span class="badge error"><?= View::e($delivery->label()) ?></span>
<?php } else { ?>
<span class="badge muted"><?= View::e($delivery->label()) ?></span>
<?php } ?>
</td>
<td class="hide-sm mono small">
<?= (int) $delivery->raw('response_status') > 0 ? (int) $delivery->raw('response_status') : '—' ?>
<?php if ((string) $delivery->raw('error') !== '') { ?>
<div class="muted break"><?= View::e((string) $delivery->raw('error')) ?></div>
<?php } ?>
</td>
<td class="hide-sm"><?= (int) $delivery->raw('attempts') ?></td>
<td class="hide-sm muted small"><?= (int) $delivery->raw('duration_ms') ?> мс</td>
<td class="muted small"><?= View::e(View::date((string) $delivery->raw('created_at'))) ?></td>
</tr>
<?php } ?>
</table>
</div>
<?= View::partial('pagination', [
'route' => 'admin.webhooks.show',
'page' => $deliveries['page'],
'pages' => $deliveries['pages'],
'params' => ['id' => $webhook->id()],
]) ?>
<?php } ?>
</div>
<?php } ?>
+109
View File
@@ -0,0 +1,109 @@
<?php
declare(strict_types=1);
/**
* Подписки на события.
*
* @var array{items: array<int, \Rsgrinko\Proton\Models\Webhook>, total: int, page: int, pages: int, per_page: int} $page
* @var array<string, array<string, string>> $groups события по разделам
* @var array<string, int> $stats посылки по состояниям
*/
use Rsgrinko\Proton\Models\Webhook;
use Rsgrinko\Proton\Models\WebhookDelivery;
use Rsgrinko\Proton\View\View;
$events = 0;
foreach ($groups as $group) {
$events += count($group);
}
?>
<h1>Вебхуки</h1>
<div class="card">
<p class="muted small">
Подписка получает событие приложения посылкой POST с подписью в заголовке
<span class="mono">X-Proton-Signature</span>. Отправляет их воркер: упавшую посылку
он повторит, а подписчик, молчащий слишком долго, отключится сам.
Событий в реестре: <?= $events ?>.
</p>
<p class="muted small">
Посылки: доставлено <?= (int) ($stats[WebhookDelivery::SENT] ?? 0) ?>,
в очереди <?= (int) ($stats[WebhookDelivery::PENDING] ?? 0) ?>,
не доставлено <?= (int) ($stats[WebhookDelivery::FAILED] ?? 0) ?>.
</p>
<div class="row">
<a class="btn primary" href="<?= View::e(View::route('admin.webhooks.create')) ?>">Новая подписка</a>
</div>
</div>
<div class="card">
<h2>Подписки</h2>
<?php if ($page['items'] === []) { ?>
<p class="muted">Подписок пока нет.</p>
<?php } else { ?>
<div class="table-wrap">
<table class="list">
<tr class="head">
<th>Название</th>
<th>Адрес</th>
<th class="hide-sm">События</th>
<th>Состояние</th>
<th class="hide-sm">Последняя посылка</th>
<th></th>
</tr>
<?php foreach ($page['items'] as $webhook) { ?>
<tr>
<td>
<a href="<?= View::e(View::route('admin.webhooks.show', ['id' => $webhook->id()])) ?>">
<?= View::e((string) $webhook->name) ?>
</a>
</td>
<td class="mono small break"><?= View::e((string) $webhook->url) ?></td>
<td class="hide-sm muted small">
<?php if (in_array(Webhook::ALL_EVENTS, $webhook->events(), true)) { ?>
все
<?php } else { ?>
<?= count($webhook->events()) ?>
<?php } ?>
</td>
<td>
<?php if ((bool) $webhook->active) { ?>
<span class="badge ok">включена</span>
<?php } else { ?>
<span class="badge muted">отключена</span>
<?php } ?>
</td>
<td class="hide-sm muted small">
<?= View::e(View::ago((string) $webhook->raw('last_sent_at'))) ?>
<?php if ((int) $webhook->raw('last_status') > 0) { ?>
<span class="mono">(<?= (int) $webhook->raw('last_status') ?>)</span>
<?php } ?>
</td>
<td class="right">
<div class="row end">
<form method="post" action="<?= View::e(View::route('admin.webhooks.test', ['id' => $webhook->id()])) ?>">
<?= View::csrf() ?>
<button type="submit">Проверить</button>
</form>
</div>
</td>
</tr>
<?php } ?>
</table>
</div>
<?= View::partial('pagination', [
'route' => 'admin.webhooks',
'page' => $page['page'],
'pages' => $page['pages'],
'params' => [],
]) ?>
<?php } ?>
</div>
+13
View File
@@ -17,6 +17,7 @@ use App\Controllers\Admin\RolesController;
use App\Controllers\Admin\SystemController;
use App\Controllers\Admin\TokensController;
use App\Controllers\Admin\UsersController;
use App\Controllers\Admin\WebhooksController;
use Rsgrinko\Proton\Access\Permission;
use Rsgrinko\Proton\Http\Router;
@@ -51,6 +52,18 @@ return static function (Router $router): void {
$router->post('/{id:\d+}/delete', [TokensController::class, 'delete'])->name('admin.tokens.delete');
});
$router->group(['prefix' => '/webhooks', 'middleware' => 'can:' . Permission::WEBHOOKS_MANAGE], function (Router $router): void {
$router->get('', [WebhooksController::class, 'index'])->name('admin.webhooks');
$router->get('/new', [WebhooksController::class, 'create'])->name('admin.webhooks.create');
$router->post('/new', [WebhooksController::class, 'store']);
$router->get('/{id:\d+}', [WebhooksController::class, 'show'])->name('admin.webhooks.show');
$router->post('/{id:\d+}', [WebhooksController::class, 'update']);
$router->post('/{id:\d+}/test', [WebhooksController::class, 'test'])->name('admin.webhooks.test');
$router->post('/{id:\d+}/toggle', [WebhooksController::class, 'toggle'])->name('admin.webhooks.toggle');
$router->post('/{id:\d+}/secret', [WebhooksController::class, 'rotate'])->name('admin.webhooks.rotate');
$router->post('/{id:\d+}/delete', [WebhooksController::class, 'delete'])->name('admin.webhooks.delete');
});
$router->get('/audit', [AuditController::class, 'index'])
->middleware('can:' . Permission::AUDIT_VIEW)
->name('admin.audit');
+73 -1
View File
@@ -19,6 +19,8 @@ use Rsgrinko\Proton\Http\Response;
use Rsgrinko\Proton\Models\ApiToken;
use Rsgrinko\Proton\Models\Role;
use Rsgrinko\Proton\Models\User;
use Rsgrinko\Proton\Models\Webhook;
use Rsgrinko\Proton\Models\WebhookDelivery;
/**
* Запрос к ядру от лица пользователя (или гостя, если его нет).
@@ -94,6 +96,27 @@ function httpUser(): User
return $user;
}
/**
* Подписка на события для обхода страниц панели.
*/
function httpWebhook(): Webhook
{
static $webhook = null;
if ($webhook instanceof Webhook) {
return $webhook;
}
$webhook = Webhook::add('Подписка для обхода', 'https://example.com/hook', [Webhook::ALL_EVENTS]);
afterTests(static function () use ($webhook): void {
WebhookDelivery::query()->where('webhook_id', $webhook->id())->delete();
$webhook->delete();
});
return $webhook;
}
test('http: гостя уводит на вход, а не показывает страницу', function (): void {
// Пользователь в базе нужен: пока их нет, всё уводит на первый запуск
httpAdmin();
@@ -148,6 +171,7 @@ test('http: все страницы администратора отвечаю
'/admin', '/admin/users', '/admin/users/new', '/admin/users/' . httpAdmin()->id(),
'/admin/roles', '/admin/roles/new', '/admin/roles/' . (Role::admin()?->id() ?? 1),
'/admin/tokens', '/admin/audit', '/admin/logs', '/admin/system',
'/admin/webhooks', '/admin/webhooks/new', '/admin/webhooks/' . httpWebhook()->id(),
];
foreach ($paths as $path) {
@@ -156,7 +180,12 @@ test('http: все страницы администратора отвечаю
});
test('http: обычный пользователь не попадает в служебные разделы', function (): void {
foreach (['/admin', '/admin/users', '/admin/roles', '/admin/tokens', '/admin/audit', '/admin/logs', '/admin/system'] as $path) {
$closed = [
'/admin', '/admin/users', '/admin/roles', '/admin/tokens',
'/admin/audit', '/admin/logs', '/admin/system', '/admin/webhooks',
];
foreach ($closed as $path) {
assertStatus(403, httpRequest('GET', $path, httpUser()), 'закрытая страница ' . $path);
}
@@ -215,6 +244,49 @@ test('http: неверные данные возвращают человека
assertSame(0, Note::query()->where('title', '')->count());
});
test('http: подписка на события заводится и проверяется из панели', function (): void {
$response = httpRequest('POST', '/admin/webhooks/new', httpAdmin(), [
'name' => 'Через форму',
'url' => 'https://example.com/hooks/proton',
'events' => ['user.login'],
'secret' => 'секрет-из-формы',
]);
assertStatus(302, $response);
/** @var Webhook $webhook */
$webhook = assertNotNull(Webhook::query()->where('name', 'Через форму')->first());
assertSame('секрет-из-формы', $webhook->secret());
assertSame(['user.login'], $webhook->events());
// Пробная посылка только встаёт в очередь — в сеть тесты не ходят
assertStatus(302, httpRequest('POST', '/admin/webhooks/' . $webhook->id() . '/test', httpAdmin()));
$delivery = assertNotNull(
WebhookDelivery::query()->where('webhook_id', $webhook->id())->orderBy('id', 'desc')->first()
);
assertSame(WebhookDelivery::PENDING, (string) $delivery->raw('status'));
// Событие без подписчиков посылок не создаёт, с подписчиком — создаёт
Rsgrinko\Proton\Webhooks\Webhooks::dispatch('user.logout', ['login' => 'кто-то']);
assertSame(1, WebhookDelivery::query()->where('webhook_id', $webhook->id())->count(), 'чужое событие не уехало');
Rsgrinko\Proton\Webhooks\Webhooks::dispatch('user.login', ['login' => 'кто-то']);
assertSame(2, WebhookDelivery::query()->where('webhook_id', $webhook->id())->count());
// Отключение и удаление — тоже из панели
assertStatus(302, httpRequest('POST', '/admin/webhooks/' . $webhook->id() . '/toggle', httpAdmin()));
assertFalse((bool) assertNotNull(Webhook::find($webhook->id()))->active);
assertStatus(302, httpRequest('POST', '/admin/webhooks/' . $webhook->id() . '/delete', httpAdmin()));
assertNull(Webhook::find($webhook->id()));
assertSame(0, WebhookDelivery::query()->where('webhook_id', $webhook->id())->count(), 'журнал ушёл вместе с подпиской');
});
test('http: неизвестный адрес — 404', function (): void {
assertStatus(404, httpRequest('GET', '/нет-такой-страницы', httpAdmin()));
});