Skip to content

Commit 281444a

Browse files
committed
in browser view, handle invalid user input properly
1 parent 69b1ad2 commit 281444a

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

finder/browser/views.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
from django.contrib.sites.shortcuts import get_current_site
2-
from django.core.exceptions import BadRequest, ObjectDoesNotExist
2+
from django.core.exceptions import BadRequest, ObjectDoesNotExist, ValidationError
33
from django.core.files.storage import default_storage
44
from django.db.models import QuerySet, Subquery
55
from django.forms.renderers import DjangoTemplates
66
from django.http import JsonResponse, HttpResponseBadRequest, HttpResponseNotFound
77
from django.utils.decorators import method_decorator
88
from django.utils.html import strip_spaces_between_tags
99
from django.utils.safestring import mark_safe
10+
from django.utils.translation import gettext_lazy as _
1011
from django.views import View
1112
from django.views.decorators.http import require_GET, require_http_methods, require_POST
1213

@@ -40,6 +41,8 @@ def dispatch(self, request, *args, **kwargs):
4041
return HttpResponseBadRequest(f"Action {self.action} not allowed.")
4142
try:
4243
return JsonResponse(action(request, *args, **kwargs))
44+
except ValidationError as e:
45+
return JsonResponse({'error': e.messages}, status=422)
4346
except Exception as e:
4447
return HttpResponseBadRequest(str(e))
4548

@@ -262,7 +265,15 @@ def change(self, request, file_id):
262265
@method_decorator(require_POST)
263266
def crop(self, request, image_id):
264267
image = FileModel.objects.get_inode(id=image_id, mime_types=['image/*'], is_folder=False)
265-
width, height = int(request.POST.get('width')), int(request.POST.get('height'))
268+
width, height = request.POST.get('width'), request.POST.get('height')
269+
width = int(width) if str(width).isdigit() else None
270+
height = int(height) if str(height).isdigit() else None
271+
if width is None and height is None:
272+
raise ValidationError(_("At least one of width or height must be given."))
273+
if width is None:
274+
width = round(height * image.width / image.height)
275+
if height is None:
276+
height = round(width / image.width * image.height)
266277
cropped_image_path = image.get_cropped_path(width, height)
267278
if not default_storage.exists(cropped_image_path):
268279
image.crop(cropped_image_path, width, height)

0 commit comments

Comments
 (0)