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

@@ -4,7 +4,6 @@ declare(strict_types=1);
class AdminController extends Controller
{
private const MEDIA_PICKER_LIMIT = 60;
private const UPLOAD_MAX_BYTES = 10 * 1024 * 1024;
public function beforeRoute(): void
@@ -28,52 +27,52 @@ class AdminController extends Controller
public function create(): void
{
$this->postForm('Nouvel article', $this->f3->alias('post_store'), Post::blank());
$this->renderPostForm('Nouvel article', $this->f3->alias('post_store'), Post::blank());
}
public function store(): void
{
$this->checkCsrf();
$input = $this->postInput();
$this->verifyCsrf();
$input = $this->readPostInput();
try {
(new Post())->savePost($input);
$this->flash('success', 'Article créé.');
$this->f3->reroute('@dashboard');
} catch (RuntimeException $e) {
$this->postForm('Nouvel article', $this->f3->alias('post_store'), $input, $e->getMessage());
$this->renderPostForm('Nouvel article', $this->f3->alias('post_store'), $input, $e->getMessage());
}
}
public function edit(): void
{
$post = (new Post())->findForForm((int) $this->f3->get('PARAMS.id'));
if (!$post) {
if ($post === null) {
$this->f3->error(404);
return;
}
$this->postForm('Modifier l\'article', $this->f3->alias('post_update', ['id' => $post['id']]), $post);
$this->renderPostForm('Modifier l\'article', $this->f3->alias('post_update', ['id' => $post['id']]), $post);
}
public function update(): void
{
$this->checkCsrf();
$this->verifyCsrf();
$id = (int) $this->f3->get('PARAMS.id');
$input = $this->postInput() + ['id' => $id];
$input = $this->readPostInput() + ['id' => $id];
try {
(new Post())->savePost($input, $id);
$this->flash('success', 'Article mis à jour.');
$this->f3->reroute('@dashboard');
} catch (RuntimeException $e) {
$this->postForm('Modifier l\'article', $this->f3->alias('post_update', ['id' => $id]), $input, $e->getMessage());
$this->renderPostForm('Modifier l\'article', $this->f3->alias('post_update', ['id' => $id]), $input, $e->getMessage());
}
}
public function delete(): void
{
$this->checkCsrf();
$this->verifyCsrf();
try {
(new Post())->deleteById((int) $this->f3->get('PARAMS.id'));
@@ -95,25 +94,27 @@ class AdminController extends Controller
'items' => $result['items'],
'pagination' => $result['pagination'],
'paginationAlias' => 'media_index',
'adminMode' => true,
]);
}
public function mediaUpload(): void
{
$this->checkCsrf();
$this->verifyCsrf();
try {
$original = (string) ($this->f3->get('FILES.image.name') ?: '');
$originalName = (string) ($this->f3->get('FILES.image.name') ?: '');
$received = Web::instance()->receive(
fn(array $file): bool => (int) ($file['size'] ?? 0) > 0 && (int) ($file['size'] ?? 0) <= self::UPLOAD_MAX_BYTES,
overwrite: false
);
$path = array_key_first(array_filter($received));
if (!$path) {
throw new RuntimeException('Choisis une image valide à envoyer.');
throw new RuntimeException('Choisis une image JPG ou PNG valide.');
}
(new Media())->upload($path, $original);
(new Media())->upload($path, $originalName);
$this->flash('success', 'Image ajoutée.');
} catch (RuntimeException $e) {
$this->flash('error', $e->getMessage());
@@ -124,11 +125,14 @@ class AdminController extends Controller
public function mediaAlt(): void
{
$this->checkCsrf();
$this->verifyCsrf();
try {
(new Media())->updateAlt((int) $this->f3->get('PARAMS.id'), $this->f3->clean((string) ($this->f3->get('POST.alt') ?: '')));
$this->flash('success', 'Texte alternatif mis à jour.');
(new Media())->updateAlt(
(int) $this->f3->get('PARAMS.id'),
$this->f3->clean((string) ($this->f3->get('POST.alt') ?: ''))
);
$this->flash('success', 'Texte alternatif enregistré.');
} catch (RuntimeException $e) {
$this->flash('error', $e->getMessage());
}
@@ -138,17 +142,18 @@ class AdminController extends Controller
public function mediaDelete(): void
{
$this->checkCsrf();
$this->verifyCsrf();
try {
$media = new Media();
$item = $media->findById((int) $this->f3->get('PARAMS.id'));
if (!$item) {
if ($item === null) {
throw new RuntimeException('Image introuvable.');
}
if ((new Post())->usesMedia($item['file_name'])) {
throw new RuntimeException('Cette image est encore utilisée par un article.');
throw new RuntimeException('Cette image est utilisée dans un article.');
}
$media->deleteById($item['id']);
$this->flash('success', 'Image supprimée.');
} catch (RuntimeException $e) {
@@ -158,27 +163,22 @@ class AdminController extends Controller
$this->f3->reroute('@media_index');
}
private function postForm(string $title, string $action, array $post, ?string $error = null): void
private function renderPostForm(string $title, string $action, array $post, ?string $error = null): void
{
$media = new Media();
$items = $media->recent(self::MEDIA_PICKER_LIMIT);
$count = $media->count();
$flash = $error ? [['type' => 'error', 'message' => $error]] : [];
$this->render('admin/post_form.html', [
'pageTitle' => $title,
'formAction' => $action,
'post' => $post,
'mediaItems' => $items,
'mediaCount' => $count,
'mediaPickerLimit' => self::MEDIA_PICKER_LIMIT,
'mediaPickerTruncated' => $count > count($items),
'titleMax' => Post::TITLE_MAX_LENGTH,
'excerptMax' => Post::EXCERPT_MAX_LENGTH,
'flash' => $error ? [['type' => 'error', 'message' => $error]] : [],
'flash' => $flash,
'adminMode' => true,
]);
}
private function postInput(): array
private function readPostInput(): array
{
return [
'title' => $this->f3->clean((string) ($this->f3->get('POST.title') ?: '')),

View File

@@ -6,7 +6,7 @@ class AuthController extends Controller
{
public function show(): void
{
if ($this->user()) {
if ($this->currentUser()) {
$this->f3->reroute('@dashboard');
return;
}
@@ -16,10 +16,11 @@ class AuthController extends Controller
public function login(): void
{
$this->checkCsrf();
$this->verifyCsrf();
$user = new User();
$auth = new Auth($user, ['id' => 'username', 'pw' => 'password_hash'], 'password_verify');
$ok = $auth->login(
$this->f3->clean((string) ($this->f3->get('POST.username') ?: '')),
(string) ($this->f3->get('POST.password') ?: '')
@@ -27,7 +28,7 @@ class AuthController extends Controller
if (!$ok) {
usleep(1000000);
$this->flash('error', 'Identifiants invalides.');
$this->flash('error', 'Identifiants incorrects.');
$this->f3->reroute('@login');
return;
}
@@ -41,11 +42,11 @@ class AuthController extends Controller
public function logout(): void
{
$this->checkCsrf();
$this->verifyCsrf();
$this->f3->clear('SESSION.user_id');
session_regenerate_id(true);
$this->rotateCsrf();
$this->flash('success', 'Déconnexion effectuée.');
$this->flash('success', 'Déconnexion réussie.');
$this->f3->reroute('@login');
}
}

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') ?: [];

View File

@@ -20,7 +20,7 @@ class SiteController extends Controller
public function show(): void
{
$post = (new Post())->findBySlug((string) $this->f3->get('PARAMS.slug'));
if (!$post) {
if ($post === null) {
$this->f3->error(404);
return;
}