BlueGit

projects-timfalken-com verhalenboek

Files

verhalenboek / web / api.php

api.php

feat: toon het overzicht per kalenderweek
timfa project_87242033_bot_b167a9be22027ad5a4b431d0ad8426c6 · pushed by timfa · 6 weeks ago
d8e294f1 History
api.php 6.6 KiB Download Raw
1<?php
2declare(strict_types=1);
3require __DIR__.'/lib/bootstrap.php';
4
5try {
6 $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
7 $route = apiRoute();
8 $actor = authenticate();
9 if ($method !== 'GET' && $method !== 'HEAD') requireCsrf($actor);
10 $readerId = $actor['kind'] === 'user' ? $actor['userId'] : null;
11
12 if ($route === '/me') {
13 if ($method !== 'GET') fail('Deze methode is hier niet toegestaan.', 405);
14 jsonOut([
15 'user' => publicUser($actor['userId']),
16 'csrf' => $actor['kind'] === 'user' ? ($_SESSION['csrf'] ?? null) : null,
17 'local' => localDev(),
18 'auth' => $actor['kind'],
19 ]);
20 }
21 if ($route === '/me/settings') {
22 if ($method !== 'PUT') fail('Deze methode is hier niet toegestaan.', 405);
23 requireReader($actor);
24 jsonOut(['user' => saveSettings($actor['userId'], readJson())]);
25 }
26 if ($route === '/me/export') {
27 if ($method !== 'GET') fail('Deze methode is hier niet toegestaan.', 405);
28 requireReader($actor);
29 header('Content-Disposition: attachment; filename="verhalenboek-gegevens.json"');
30 jsonOut(exportUser($actor['userId']));
31 }
32 if ($route === '/session/switch') {
33 if ($method !== 'POST') fail('Deze methode is hier niet toegestaan.', 405);
34 requireReader($actor);
35 if (!localDev()) fail('Niet beschikbaar.', 403);
36 $in = readJson();
37 if (!in_array($in['user'] ?? '', ['test_user_1', 'test_user_2'], true)) throw new AppException('Onbekende testgebruiker.');
38 loginUser('local:'.$in['user'], $in['user']);
39 jsonOut(['ok' => true, 'user' => publicUser($_SESSION['user']), 'csrf' => $_SESSION['csrf']]);
40 }
41 if ($route === '/session/logout') {
42 if ($method !== 'POST') fail('Deze methode is hier niet toegestaan.', 405);
43 requireReader($actor);
44 if (!localDev() && isset($_SESSION['token'])) {
45 try { authRequest('/api/logout', [], (string)$_SESSION['token']); } catch (Throwable $e) { /* lokaal alsnog afmelden */ }
46 }
47 $_SESSION = [];
48 session_destroy();
49 jsonOut(['ok' => true]);
50 }
51 if ($route === '/keys') {
52 requireAdminSession($actor);
53 if ($method === 'GET') jsonOut(['keys' => listApiKeys()]);
54 if ($method === 'POST') {
55 $in = readJson();
56 jsonOut(['key' => createApiKey($actor['userId'], $in['name'] ?? null)], 201);
57 }
58 fail('Deze methode is hier niet toegestaan.', 405);
59 }
60 if ($route === '/users') {
61 requireAdminSession($actor, 'Alleen een beheerder mag gebruikers beheren.', 'users');
62 if ($method !== 'GET') fail('Deze methode is hier niet toegestaan.', 405);
63 jsonOut(['users' => listUsers()]);
64 }
65 if (preg_match('#^/users/([^/]+)$#', $route, $match)) {
66 requireAdminSession($actor, 'Alleen een beheerder mag gebruikers beheren.', 'users');
67 if ($method !== 'PUT') fail('Deze methode is hier niet toegestaan.', 405);
68 $in = readJson();
69 if (!is_bool($in['admin'] ?? null)) throw new AppException('Zeg of deze gebruiker beheerder moet zijn.');
70 jsonOut(['user' => setUserRole($actor['userId'], rawurldecode($match[1]), $in['admin'])]);
71 }
72 if (preg_match('#^/keys/(\d+)$#', $route, $match)) {
73 requireAdminSession($actor);
74 if ($method === 'GET') jsonOut(['key' => revealApiKey((int)$match[1])]);
75 if ($method === 'DELETE') jsonOut(['key' => revokeApiKey((int)$match[1])]);
76 fail('Deze methode is hier niet toegestaan.', 405);
77 }
78 if ($route === '/days') {
79 if ($method === 'GET') {
80 $week = $_GET['week'] ?? null;
81 $today = $_GET['today'] ?? null;
82 if ($week !== null && !is_string($week)) throw new AppException('De week moet een datum zijn.');
83 if ($today !== null && !is_string($today)) throw new AppException('De datum moet de vorm JJJJ-MM-DD hebben.');
84 $listed = listDays($readerId);
85 $focus = overviewWeek($readerId, is_string($week) ? $week : null, is_string($today) ? $today : null);
86 jsonOut([
87 'days' => $listed,
88 'weekDays' => daysInWeek($listed, $focus['week']['start'], $focus['week']['end']),
89 'lastRead' => $focus['lastRead'],
90 'week' => $focus['week'],
91 ]);
92 }
93 if ($method === 'POST') {
94 requireWriter($actor);
95 $in = readJson();
96 if (!is_string($in['date'] ?? null)) throw new AppException('De datum moet de vorm JJJJ-MM-DD hebben.');
97 jsonOut(createDay($in['date'], $in['title'] ?? null, $in['stories'] ?? null), 201);
98 }
99 fail('Deze methode is hier niet toegestaan.', 405);
100 }
101 if ($route === '/days/latest') {
102 if ($method !== 'GET') fail('Deze methode is hier niet toegestaan.', 405);
103 jsonOut(latestWritten());
104 }
105 if ($route === '/days/gaps') {
106 if ($method !== 'GET') fail('Deze methode is hier niet toegestaan.', 405);
107 jsonOut(dayGaps());
108 }
109 if (preg_match('#^/days/(\d{4}-\d{2}-\d{2})$#', $route, $match)) {
110 $date = $match[1];
111 if ($method === 'GET') jsonOut(loadDay($date, $readerId));
112 if ($method === 'PUT') {
113 requireWriter($actor);
114 jsonOut(updateDay($date, readJson()));
115 }
116 if ($method === 'DELETE') {
117 requireWriter($actor);
118 jsonOut(['ok' => true, 'date' => deleteDay($date)]);
119 }
120 fail('Deze methode is hier niet toegestaan.', 405);
121 }
122 if (preg_match('#^/days/(\d{4}-\d{2}-\d{2})/read$#', $route, $match)) {
123 requireReader($actor);
124 if ($method === 'POST') jsonOut(markRead($actor['userId'], $match[1], true));
125 if ($method === 'DELETE') jsonOut(markRead($actor['userId'], $match[1], false));
126 fail('Deze methode is hier niet toegestaan.', 405);
127 }
128 if (preg_match('#^/days/(\d{4}-\d{2}-\d{2})/stories$#', $route, $match)) {
129 if ($method !== 'POST') fail('Deze methode is hier niet toegestaan.', 405);
130 requireWriter($actor);
131 jsonOut(addStory($match[1], readJson()), 201);
132 }
133 if (preg_match('#^/days/(\d{4}-\d{2}-\d{2})/stories/([123])$#', $route, $match)) {
134 requireWriter($actor);
135 if ($method === 'PUT') jsonOut(updateStory($match[1], (int)$match[2], readJson()));
136 if ($method === 'DELETE') jsonOut(deleteStory($match[1], (int)$match[2]));
137 fail('Deze methode is hier niet toegestaan.', 405);
138 }
139 fail('Onbekend pad.', 404);
140} catch (AppException $e) {
141 fail($e->getMessage(), $e->status, $e->auth);
142} catch (Throwable $e) {
143 error_log($e->getMessage());
144 fail('Er ging iets mis.', 500);
145}