2021-10-05 12:25:42 +02:00
|
|
|
# validators.py
|
|
|
|
#
|
|
|
|
# validators for file uploads, etc.
|
|
|
|
|
2022-10-09 22:51:32 +02:00
|
|
|
from django.utils.translation import gettext as _
|
2024-02-20 22:57:39 +01:00
|
|
|
from helpdesk import settings as helpdesk_settings
|
2021-10-05 12:25:42 +02:00
|
|
|
|
2022-07-22 03:26:41 +02:00
|
|
|
|
2022-07-12 12:34:19 +02:00
|
|
|
# TODO: can we use the builtin Django validator instead?
|
|
|
|
# see:
|
|
|
|
# https://docs.djangoproject.com/en/4.0/ref/validators/#fileextensionvalidator
|
|
|
|
|
|
|
|
|
2021-10-05 12:25:42 +02:00
|
|
|
def validate_file_extension(value):
|
|
|
|
from django.core.exceptions import ValidationError
|
2022-07-22 03:26:41 +02:00
|
|
|
import os
|
2021-10-05 12:25:42 +02:00
|
|
|
ext = os.path.splitext(value.name)[1] # [0] returns path+filename
|
|
|
|
# TODO: we might improve this with more thorough checks of file types
|
|
|
|
# rather than just the extensions.
|
2021-12-31 23:59:37 +01:00
|
|
|
|
2024-02-20 22:57:39 +01:00
|
|
|
if not helpdesk_settings.HELPDESK_VALIDATE_ATTACHMENT_TYPES:
|
|
|
|
return
|
2021-12-31 23:59:37 +01:00
|
|
|
|
2024-02-20 22:57:39 +01:00
|
|
|
if ext.lower() not in helpdesk_settings.HELPDESK_VALID_EXTENSIONS:
|
2022-07-12 12:34:19 +02:00
|
|
|
# TODO: one more check in case it is a file with no extension; we
|
|
|
|
# should always allow that?
|
2022-04-22 20:52:51 +02:00
|
|
|
if not (ext.lower() == '' or ext.lower() == '.'):
|
2022-07-12 12:34:19 +02:00
|
|
|
raise ValidationError(
|
2022-10-09 22:51:32 +02:00
|
|
|
_('Unsupported file extension: ') + ext.lower()
|
|
|
|
)
|