-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapi.php
More file actions
419 lines (358 loc) · 14.4 KB
/
Copy pathapi.php
File metadata and controls
419 lines (358 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
<?php
declare(strict_types=1);
namespace Grav\Plugin;
use Composer\Autoload\ClassLoader;
use Grav\Common\Plugin;
use Grav\Common\Processors\Events\RequestHandlerEvent;
use Grav\Common\Utils;
use Grav\Events\PermissionsRegisterEvent;
use Grav\Framework\Acl\PermissionsReader;
use Grav\Plugin\Api\ApiRouter;
use Grav\Plugin\Api\Audit\AuditStore;
use Grav\Plugin\Api\Audit\AuditSubscriber;
use Grav\Plugin\Api\Auth\ApiKeyManager;
use Grav\Plugin\Api\Popularity\PopularityTracker;
use Grav\Plugin\Api\Webhooks\WebhookDispatcher;
use RocketTheme\Toolbox\Event\Event;
class ApiPlugin extends Plugin
{
public $features = [
'blueprints' => 1000,
];
protected $active = false;
protected string $base = '';
protected string $apiRoute = '';
public static function getSubscribedEvents(): array
{
return [
'onPluginsInitialized' => [
['setup', 100000],
['onPluginsInitialized', 1001],
],
'onRequestHandlerInit' => [
['onRequestHandlerInit', 99000],
],
'onBeforeCacheClear' => ['onBeforeCacheClear', 0],
PermissionsRegisterEvent::class => ['onRegisterPermissions', 1000],
];
}
public function autoload(): ClassLoader
{
return require __DIR__ . '/vendor/autoload.php';
}
/**
* Early setup - determine if we're on an API route.
*/
public function setup(): void
{
$route = $this->config->get('plugins.api.route');
if (!$route) {
return;
}
$this->base = '/' . trim($route, '/');
$prefix = $this->config->get('plugins.api.version_prefix', 'v1');
$this->apiRoute = $this->base . '/' . $prefix;
$uri = $this->grav['uri'];
$currentPath = $uri->path();
// On subpath installs (e.g. /sync-testing/grav-c) $uri->path() may
// include Grav's base; strip it before testing the api prefix so
// the plugin still activates and the api router gets installed.
$gravBase = rtrim((string)$uri->rootUrl(false), '/');
if ($gravBase !== '' && str_starts_with($currentPath, $gravBase)) {
$currentPath = substr($currentPath, strlen($gravBase)) ?: '/';
}
if (str_starts_with($currentPath, $this->base)) {
$this->active = true;
}
}
public function onPluginsInitialized(): void
{
// Register webhook event listeners (always active, not just on API routes)
$this->registerWebhookListeners();
// Register audit-trail listeners (always active; each listener checks the
// audit.enabled flag at fire time, so this is a no-op when the feature is
// off (it is off by default)..
$this->registerAuditListeners();
// Page-view tracking subscribes for FRONTEND requests only — the
// handler itself short-circuits for admin/API/non-page requests.
if (!$this->active && !$this->isAdmin()) {
$this->enable([
'onPageInitialized' => ['onFrontendPageInitialized', 0],
]);
}
if ($this->active) {
// Keep the object cache warm for API requests even when the global
// cache is switched off. Disabling cache is a frontend-dev workflow
// (see fresh template/page output) — but the API renders no Twig and
// no frontend pages, so for it cache-off buys nothing and forces a
// full page-tree rebuild on every one of the SPA's many small calls
// (admin2#65). This runs before PagesProcessor builds the index, so
// the override is in place when the page index is first fetched.
if ($this->config->get('plugins.api.force_cache', true)) {
$this->grav['cache']->setEnabled(true);
}
// Disable pages processing for API requests - we don't need Twig/templates
$this->grav['pages']->disablePages();
// Register the plugin's templates path so server-side operations
// that need to render Twig (e.g. password reset emails composed
// by AuthController) can find emails/api/*.html.twig.
$this->enable([
'onTwigTemplatePaths' => ['onTwigTemplatePaths', 0],
// Disable the audit toggle in the plugin's own config form when
// the SQLite backend the trail depends on isn't available.
'onApiBlueprintResolved' => ['onApiBlueprintResolved', 0],
]);
return;
}
// Handle admin API key tasks and templates
if ($this->isAdmin()) {
// Intercept API key tasks early, before admin's Flex routing
$this->handleAdminApiKeyTask();
$this->enable([
'onTwigTemplatePaths' => ['onTwigTemplatePaths', 0],
'onTwigExtensions' => ['onTwigExtensions', 0],
]);
}
}
/**
* Register Twig function to read API keys from centralized store.
*/
public function onTwigExtensions(): void
{
$manager = new ApiKeyManager();
$this->grav['twig']->twig()->addFunction(
new \Twig\TwigFunction('api_keys_for_user', function (string $username) use ($manager) {
$accounts = $this->grav['accounts'];
$user = $accounts->load($username);
if (!$user->exists()) {
return [];
}
return $manager->listKeys($user);
})
);
}
/**
* Check for and handle API key admin tasks directly.
* This runs before admin's Flex controller, which doesn't fire onAdminTaskExecute.
*/
protected function handleAdminApiKeyTask(): void
{
$uri = $this->grav['uri'];
$task = $uri->param('task') ?? $_POST['task'] ?? null;
if (!$task || !in_array($task, ['apiKeyGenerate', 'apiKeyRevoke'], true)) {
return;
}
// Validate nonce
$nonce = $uri->param('admin-nonce') ?? $_POST['admin-nonce'] ?? null;
if (!$nonce || !Utils::verifyNonce($nonce, 'admin-form')) {
$this->outputJson(['status' => 'error', 'message' => 'Invalid security nonce.']);
}
// Verify admin is logged in
$this->grav['session']->init();
$user = $this->grav['session']->user ?? null;
if (!$user || !$user->authorized || !$user->authorize('admin.login')) {
$this->outputJson(['status' => 'error', 'message' => 'Not authorized.']);
}
match ($task) {
'apiKeyGenerate' => $this->handleApiKeyGenerate(),
'apiKeyRevoke' => $this->handleApiKeyRevoke(),
};
}
protected function handleApiKeyGenerate(): void
{
$post = $_POST;
$username = $this->getAdminRouteUsername();
if (!$username) {
$this->outputJson(['status' => 'error', 'message' => 'Could not determine username.']);
}
$user = $this->grav['accounts']->load($username);
if (!$user->exists()) {
$this->outputJson(['status' => 'error', 'message' => "User '{$username}' not found."]);
}
$name = $post['name'] ?? 'API Key';
$expiryDays = !empty($post['expiry_days']) ? (int) $post['expiry_days'] : null;
$manager = new ApiKeyManager();
$result = $manager->generateKey($user, $name, [], $expiryDays);
$this->outputJson([
'status' => 'success',
'key' => $result['key'],
'id' => $result['id'],
'message' => 'API key generated successfully.',
]);
}
protected function handleApiKeyRevoke(): void
{
$post = $_POST;
$keyId = $post['key_id'] ?? '';
$username = $this->getAdminRouteUsername();
if (!$username || !$keyId) {
$this->outputJson(['status' => 'error', 'message' => 'Missing parameters.']);
}
$user = $this->grav['accounts']->load($username);
if (!$user->exists()) {
$this->outputJson(['status' => 'error', 'message' => "User '{$username}' not found."]);
}
$manager = new ApiKeyManager();
$revoked = $manager->revokeKey($user, $keyId);
$this->outputJson([
'status' => $revoked ? 'success' : 'error',
'message' => $revoked ? 'API key revoked.' : 'API key not found.',
]);
}
/**
* Output JSON and terminate. Used for admin AJAX tasks.
*/
protected function outputJson(array $data): never
{
header('Content-Type: application/json');
header('Cache-Control: no-store');
echo json_encode($data);
exit;
}
/**
* Extract username from admin route (e.g. /admin/accounts/admin)
*/
protected function getAdminRouteUsername(): ?string
{
$uri = $this->grav['uri'];
$path = $uri->path();
if (preg_match('#/(?:accounts|user)/([^/]+)#', $path, $matches)) {
return $matches[1];
}
return null;
}
/**
* Register plugin templates so admin can find the api_keys field type.
*/
public function onTwigTemplatePaths(): void
{
$this->grav['twig']->twig_paths[] = __DIR__ . '/templates';
}
/**
* Register the API router middleware into Grav's request pipeline.
*/
public function onRequestHandlerInit(RequestHandlerEvent $event): void
{
if (!$this->active) {
return;
}
$route = $event->getRoute();
$path = $route->getRoute();
if (str_starts_with($path, $this->base)) {
$event->addMiddleware('api_router', new ApiRouter($this->grav, $this->config));
}
}
/**
* Register webhook event listeners for all API mutation events.
*/
protected function registerWebhookListeners(): void
{
$events = WebhookDispatcher::getSubscribedEvents();
/** @var \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher */
$eventDispatcher = $this->grav['events'];
$webhookDispatcher = null;
foreach ($events as $eventName => [$method, $priority]) {
$eventDispatcher->addListener($eventName, function (Event $event) use ($eventName, &$webhookDispatcher) {
// Lazy-load dispatcher only when first event fires
if ($webhookDispatcher === null) {
$webhookDispatcher = new WebhookDispatcher();
}
$webhookDispatcher->dispatch($eventName, $event->toArray());
}, $priority);
}
}
/**
* When the API plugin's own config form is resolved for admin-next, disable
* the "Enable Audit Trail" toggle and surface a warning if SQLite (the audit
* store's backend) is not available, so it cannot be switched on with no way
* to persist the data. Backend writes already fail closed without SQLite;
* this just makes the constraint visible in the UI.
*/
public function onApiBlueprintResolved(Event $event): void
{
if (($event['plugin'] ?? null) !== 'api' || AuditStore::available()) {
return;
}
$event['fields'] = $this->annotateAuditUnavailable((array) ($event['fields'] ?? []));
}
/**
* Recursively walk the serialized field tree and, on the `audit.enabled`
* node, set `disabled` and prepend a SQLite-required warning to its help.
*
* @param array<int,array<string,mixed>> $fields
* @return array<int,array<string,mixed>>
*/
protected function annotateAuditUnavailable(array $fields): array
{
$warning = 'SQLite (the pdo_sqlite PHP extension) is required to store audit data and is not available on this server. Install it to enable the audit trail. ';
foreach ($fields as &$field) {
if (!is_array($field)) {
continue;
}
if (($field['name'] ?? null) === 'audit.enabled') {
$field['disabled'] = true;
$field['help'] = $warning . (string) ($field['help'] ?? '');
}
if (isset($field['fields']) && is_array($field['fields'])) {
$field['fields'] = $this->annotateAuditUnavailable($field['fields']);
}
}
unset($field);
return $fields;
}
/**
* Register audit-trail event listeners. Mirrors the webhook listener wiring:
* one closure per event that forwards the event name + payload to the
* AuditSubscriber. The subscriber itself is lazily created on first fire and
* short-circuits when the feature is disabled or SQLite is unavailable.
*/
protected function registerAuditListeners(): void
{
if (!AuditStore::available()) {
return;
}
/** @var \Symfony\Component\EventDispatcher\EventDispatcher $eventDispatcher */
$eventDispatcher = $this->grav['events'];
$subscriber = null;
foreach (AuditSubscriber::getSubscribedEvents() as $eventName => [$method, $priority]) {
$eventDispatcher->addListener($eventName, function (Event $event) use ($eventName, $method, &$subscriber) {
if ($subscriber === null) {
$subscriber = new AuditSubscriber();
}
$subscriber->{$method}($eventName, $event);
}, $priority);
}
}
/**
* Register API-specific permissions.
*/
/**
* Clear the API route cache when Grav cache is cleared.
*/
public function onBeforeCacheClear(\RocketTheme\Toolbox\Event\Event $event): void
{
$locator = $this->grav['locator'];
$cacheDir = $locator->findResource('cache://', true);
if ($cacheDir) {
$apiCachePath = $cacheDir . '/api';
if (is_dir($apiCachePath)) {
$paths = $event['paths'] ?? [];
$paths[] = $apiCachePath;
$event['paths'] = $paths;
}
}
}
public function onRegisterPermissions(PermissionsRegisterEvent $event): void
{
$actions = PermissionsReader::fromYaml("plugin://{$this->name}/permissions.yaml");
$event->permissions->addActions($actions);
}
/**
* Track a frontend page view. Replaces admin-classic's Popularity
* tracker so popularity stats keep working in admin-next-only installs.
*/
public function onFrontendPageInitialized(): void
{
(new PopularityTracker())->trackHit();
}
}