Skip to content

Commit

Permalink
Added some validator for image
Browse files Browse the repository at this point in the history
  • Loading branch information
fflorent-01 committed Jun 9, 2023
1 parent 53c5a7d commit 4befbe0
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 12 deletions.
7 changes: 0 additions & 7 deletions backend/api/constants/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +0,0 @@
# Could be an idea to review naming scheme so as to use:
# from api.constants import files
# then file.ALLOWED_PATH_TYPE, FILE.ALLOWED_PATH_CONTEXT, ...
# and for things like gender
# from api.constants import genders
# then use like:à
# gender.LIST, GENDER.MODEL
4 changes: 4 additions & 0 deletions backend/api/constants/mem_size.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
BYTE = 1024**0
KB = 1024**1
MB = 1024**2
GB = 1024**3
9 changes: 5 additions & 4 deletions backend/api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.core.validators import validate_ipv4_address, MaxValueValidator, MinValueValidator
from api.validators import validate_image_file_size
from uuid import uuid4
from api.constants import user_roles, relationships, genders

Expand Down Expand Up @@ -77,10 +78,10 @@ def total_created_ads(self):


class UserProfile(models.Model):
user = models.OneToOneField(
User, related_name="profile", on_delete=models.CASCADE, primary_key=True, editable=False)
profile_pic_url = models.ImageField(
upload_to="images/avatars/", default="images/avatars/default-profile-pic.webp")
user = models.OneToOneField(User, related_name="profile",
on_delete=models.CASCADE, primary_key=True, editable=False)
profile_pic_url = models.ImageField("Profile picture", upload_to="images/avatars/",
default="images/avatars/default-profile-pic.webp", validators=[validate_image_file_size])
# TODO: Test and confirm
# profile_pic_url = models.URLField(max_length=300, default=f"{settings.MEDIA_URL}images/avatars/default-profile-pic.webp")
given_name = models.CharField(max_length=35, blank=True)
Expand Down
45 changes: 45 additions & 0 deletions backend/api/validators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from math import inf
from django.core.validators import validate_image_file_extension
from rest_framework.exceptions import ValidationError
from api.constants import mem_size

# class ImageFileExtensionValidator(validate_image_file_extension):
# allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'webp']

# File size validation
def validate_file_size(file, min_size: int=0, max_size: int=inf):
""" A validator that test file min/ max size.
Args:
value (file): The file being analysed.
min_size (int, optional): Min size in bits. Defaults to 0.
max_size (int, optional): Max size in bits. Defaults to inf.
Raises:
ValueError: min_size must be positive.
ValueError: max_size must be greater or equal to min_size.
ValidationError: File size is smaller than min_size.
ValidationError: File size is greater than max_size.
"""

if min_size < 0:
raise ValueError("min_size argument must be greater or equal to 0.")
if max_size < min_size:
raise ValueError(f"max_size: {max_size} must be greater or equal than min_size: {min_size}.")

if file.size < min_size:
raise ValidationError(f"File size should be at least {min_size} bytes.") # , "min_size"
if max_size is not None and file.size > max_size:
raise ValidationError(f"File size should not exceed {max_size} bytes.") # , "max_size"

def validate_image_file_size(file, min_size=0, max_size=10*mem_size.MB):
""" Thin wrapper around validate_file_size with default min/max values for images."""
return validate_file_size(file, min_size=min_size, max_size=max_size)

def validate_audio_file_size(file, min_size=0, max_size=50*mem_size.MB):
""" Thin wrapper around validate_file_size with default min/max values for audio."""
return validate_file_size(file, min_size=min_size, max_size=max_size)

def validate_video_file_size(file, min_size=0, max_size=100*mem_size.MB):
""" Thin wrapper around validate_file_size with default min/max values for video."""
return validate_file_size(file, min_size=min_size, max_size=max_size)
5 changes: 4 additions & 1 deletion backend/django_server/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,9 @@
}

ALLOWED_HOSTS = ["localhost", "0.0.0.0", "127.0.0.1"]

APPEND_SLASH = False


# Application definition

INSTALLED_APPS = [
Expand Down Expand Up @@ -105,6 +105,9 @@
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PROXY_HEADERS': {
'HTTP_X_FORWARDED_FOR': 'X_FORWARDED_FOR',
}
}


Expand Down

0 comments on commit 4befbe0

Please sign in to comment.