Simplification

This commit is contained in:
julien
2026-03-30 15:05:13 +02:00
parent b4a80013d5
commit b4593840a8
30 changed files with 526 additions and 781 deletions

View File

@@ -13,77 +13,69 @@ abstract class Controller
protected function render(string $view, array $data = [], int $ttl = 0): void
{
$this->ensureCsrf();
$user = $this->user();
$user = $this->currentUser();
$flash = array_key_exists('flash', $data) ? $data['flash'] : $this->pullFlash();
$this->f3->expire($user ? 0 : $ttl);
$this->f3->mset($data + [
'view' => $view,
'flash' => is_array($flash) ? $flash : [],
'CSRF' => $this->csrfToken(),
'currentUser' => $user,
'flash' => is_array($flash) ? $flash : [],
'view' => $view,
'adminMode' => false,
'metaDescription' => null,
'CSRF_TOKEN' => (string) $this->f3->get('SESSION.csrf_token'),
]);
echo Template::instance()->render('layout.html');
}
protected function user(): ?array
protected function currentUser(): ?array
{
if (!$this->f3->exists('ctx.user_loaded')) {
$id = (int) ($this->f3->get('SESSION.user_id') ?: 0);
$this->f3->set('currentUser', $id > 0 ? (new User())->findPublic($id) : null);
$this->f3->set('ctx.user_loaded', true);
}
return $this->f3->get('currentUser');
$id = (int) ($this->f3->get('SESSION.user_id') ?: 0);
return $id > 0 ? (new User())->findPublic($id) : null;
}
protected function requireAuth(): void
{
if ($this->user()) {
if ($this->currentUser()) {
return;
}
$this->flash('error', 'Connecte-toi pour continuer.');
$this->flash('error', 'Connecte-toi pour accéder à cette page.');
$this->f3->reroute('@login');
}
protected function checkCsrf(): void
protected function csrfToken(): string
{
$sent = trim((string) ($this->f3->get('POST.csrf_token') ?: ''));
$expected = trim((string) ($this->f3->get('SESSION.csrf_token') ?: ''));
$token = trim((string) ($this->f3->get('SESSION.csrf') ?: ''));
if ($token === '') {
$token = bin2hex(random_bytes(32));
$this->f3->set('SESSION.csrf', $token);
}
if ($sent !== '' && $expected !== '' && hash_equals($expected, $sent)) {
return $token;
}
protected function verifyCsrf(): void
{
$sent = trim((string) ($this->f3->get('POST.csrf') ?: ''));
if ($sent !== '' && hash_equals($this->csrfToken(), $sent)) {
return;
}
$this->f3->error(400);
}
protected function rotateCsrf(): void
{
$this->f3->set('SESSION.csrf', bin2hex(random_bytes(32)));
}
protected function flash(string $type, string $message): void
{
$this->f3->push('SESSION.flash', ['type' => $type, 'message' => $message]);
}
protected function rotateCsrf(): void
{
$this->f3->clear('SESSION.csrf_token');
$this->ensureCsrf();
}
private function ensureCsrf(): void
{
if ($this->f3->exists('SESSION.csrf_token')) {
return;
}
$seed = trim((string) ($this->f3->get('CSRF') ?: ''));
$this->f3->set('SESSION.csrf_token', $seed !== '' ? $seed : bin2hex(random_bytes(16)));
}
private function pullFlash(): array
{
return $this->f3->pull('SESSION.flash') ?: [];