From c522657212fa92120001cde453474ebece4190bd Mon Sep 17 00:00:00 2001 From: Alexander Skvortsov <38059171+askvortsov1@users.noreply.github.com> Date: Wed, 1 Dec 2021 15:16:45 -0500 Subject: [PATCH] Improve avatar upload experience (#3181) Fixes https://github.com/flarum/core/issues/3055 - On the frontend, accept only image types as a hint to the OS file picker. - On the backend, add more robust validation to ensure only valid images make it through. This isn't necessary for security, but results in less confusing error mesages. --- js/src/forum/components/AvatarEditor.js | 2 +- src/User/AvatarValidator.php | 10 +++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/js/src/forum/components/AvatarEditor.js b/js/src/forum/components/AvatarEditor.js index 880b0a4df..f48d4c0d6 100644 --- a/js/src/forum/components/AvatarEditor.js +++ b/js/src/forum/components/AvatarEditor.js @@ -149,7 +149,7 @@ export default class AvatarEditor extends Component { // Create a hidden HTML input element and click on it so the user can select // an avatar file. Once they have, we will upload it via the API. - const $input = $(''); + const $input = $(''); $input .appendTo('body') diff --git a/src/User/AvatarValidator.php b/src/User/AvatarValidator.php index f9689b239..5a0a1cad2 100644 --- a/src/User/AvatarValidator.php +++ b/src/User/AvatarValidator.php @@ -11,6 +11,8 @@ namespace Flarum\User; use Flarum\Foundation\AbstractValidator; use Flarum\Foundation\ValidationException; +use Intervention\Image\Exception\NotReadableException; +use Intervention\Image\ImageManager; use Psr\Http\Message\UploadedFileInterface; use Symfony\Component\Mime\MimeTypes; @@ -69,6 +71,12 @@ class AvatarValidator extends AbstractValidator if (! in_array($guessedExtension, $allowedTypes)) { $this->raise('mimes', [':values' => implode(', ', $allowedTypes)]); } + + try { + (new ImageManager)->make($file->getStream()); + } catch (NotReadableException $_e) { + $this->raise('image'); + } } protected function assertFileSize(UploadedFileInterface $file) @@ -103,6 +111,6 @@ class AvatarValidator extends AbstractValidator protected function getAllowedTypes() { - return ['jpg', 'png', 'bmp', 'gif']; + return ['jpeg', 'jpg', 'png', 'bmp', 'gif']; } }