84 lines
2.1 KiB
PHP
84 lines
2.1 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
abstract class Controller
|
|
{
|
|
protected Base $f3;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->f3 = Base::instance();
|
|
}
|
|
|
|
protected function render(string $view, array $data = [], int $ttl = 0): void
|
|
{
|
|
$user = $this->currentUser();
|
|
$flash = array_key_exists('flash', $data) ? $data['flash'] : $this->pullFlash();
|
|
|
|
$this->f3->expire($user ? 0 : $ttl);
|
|
$this->f3->mset($data + [
|
|
'CSRF' => $this->csrfToken(),
|
|
'currentUser' => $user,
|
|
'flash' => is_array($flash) ? $flash : [],
|
|
'view' => $view,
|
|
'adminMode' => false,
|
|
'metaDescription' => null,
|
|
]);
|
|
|
|
echo Template::instance()->render('layout.html');
|
|
}
|
|
|
|
protected function currentUser(): ?array
|
|
{
|
|
$id = (int) ($this->f3->get('SESSION.user_id') ?: 0);
|
|
return $id > 0 ? (new User())->findPublic($id) : null;
|
|
}
|
|
|
|
protected function requireAuth(): void
|
|
{
|
|
if ($this->currentUser()) {
|
|
return;
|
|
}
|
|
|
|
$this->flash('error', 'Connecte-toi pour accéder à cette page.');
|
|
$this->f3->reroute('@login');
|
|
}
|
|
|
|
protected function csrfToken(): string
|
|
{
|
|
$token = trim((string) ($this->f3->get('SESSION.csrf') ?: ''));
|
|
if ($token === '') {
|
|
$token = bin2hex(random_bytes(32));
|
|
$this->f3->set('SESSION.csrf', $token);
|
|
}
|
|
|
|
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]);
|
|
}
|
|
|
|
private function pullFlash(): array
|
|
{
|
|
return $this->f3->pull('SESSION.flash') ?: [];
|
|
}
|
|
}
|