50 lines
1.9 KiB
PHP
50 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace Modules\Api\Http\Controllers;
|
|
|
|
use Illuminate\Http\RedirectResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\View\View;
|
|
use Modules\Api\Models\ApiToken;
|
|
use Modules\Api\Models\Webhook;
|
|
|
|
final class ApiController
|
|
{
|
|
public function index(): View
|
|
{
|
|
return view('api::admin.index', ['tokens' => ApiToken::with('user')->latest()->paginate(20, '*', 'tokens'), 'webhooks' => Webhook::latest()->paginate(20, '*', 'webhooks')]);
|
|
}
|
|
|
|
public function storeToken(Request $r): RedirectResponse
|
|
{
|
|
$d = $r->validate(['name' => 'required|string|max:255', 'abilities' => 'nullable|string', 'expires_at' => 'nullable|date|after:now']);
|
|
$abilities = array_values(array_filter(array_map('trim', explode(',', $d['abilities'] ?: '*'))));
|
|
[,$plain] = ApiToken::issue($r->user(), $d['name'], $abilities, isset($d['expires_at']) ? new \DateTimeImmutable($d['expires_at']) : null);
|
|
|
|
return back()->with('api_token', $plain)->with('status', 'API token created.');
|
|
}
|
|
|
|
public function destroyToken(ApiToken $token): RedirectResponse
|
|
{
|
|
$token->delete();
|
|
|
|
return back()->with('status', 'API token revoked.');
|
|
}
|
|
|
|
public function storeWebhook(Request $r): RedirectResponse
|
|
{
|
|
$d = $r->validate(['name' => 'required|string|max:255', 'url' => 'required|url|max:2048', 'events' => 'required|string', 'site_id' => 'nullable|integer|exists:sites,id']);
|
|
Webhook::create(['name' => $d['name'], 'url' => $d['url'], 'events' => array_values(array_filter(array_map('trim', explode(',', $d['events'])))), 'site_id' => $d['site_id'] ?? null, 'secret' => Str::random(48), 'is_active' => true]);
|
|
|
|
return back()->with('status', 'Webhook created.');
|
|
}
|
|
|
|
public function destroyWebhook(Webhook $webhook): RedirectResponse
|
|
{
|
|
$webhook->delete();
|
|
|
|
return back()->with('status','Webhook deleted.');
|
|
}
|
|
}
|