bartczak-pa / Cookbook

0 stars 0 forks source link

**🚨 suggestion (security):** Add validation for ImageField #3

Closed bartczak-pa closed 2 months ago

bartczak-pa commented 2 months ago
          **🚨 suggestion (security):** Add validation for ImageField

Consider adding validation for file size and type on the ImageField to enhance security and prevent potential issues with large or malicious file uploads.

from django.core.validators import FileExtensionValidator, MaxValueValidator
from django.core.exceptions import ValidationError

def validate_file_size(value):
    limit = 2 * 1024 * 1024
    if value.size > limit:
        raise ValidationError('File too large. Size should not exceed 2 MB.')

image = models.ImageField(
    upload_to="category_images/",
    blank=True,
    null=True,
    validators=[FileExtensionValidator(allowed_extensions=['jpg', 'jpeg', 'png', 'gif']), validate_file_size]
)

_Originally posted by @sourcery-ai[bot] in https://github.com/bartczak-pa/Cookbook/pull/2#discussion_r1727649490_

bartczak-pa commented 2 months ago

By default Django validates that the uploaded object is a valid image so there's no reason for additional extension validation.