Skip to content

Commit

Permalink
👌 IMPROVE: Add python-magic library for file type identification
Browse files Browse the repository at this point in the history
  • Loading branch information
aottr committed Mar 11, 2024
1 parent b6dd0ff commit f148c9f
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
13 changes: 12 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ Django = "^5.0.3"
django-colorfield = "^0.11.0"
google-auth = "^2.28.2"
google-auth-oauthlib = "^1.2.0"
python-magic = "^0.4.27"


[build-system]
Expand Down
32 changes: 32 additions & 0 deletions ticketing/forms.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from django import forms
from .models import Ticket, Template, Team, Category
from django.utils.translation import gettext_lazy as _
import magic


class MultipleFileInput(forms.ClearableFileInput):
Expand Down Expand Up @@ -29,6 +30,13 @@ class CommentForm(forms.Form):
attrs={'class': 'toggle toggle-error'}), required=False)


ATTACHMENT_CONTENT_TYPES = [
'image/jpeg',
'image/png',
'application/pdf'
]


class TicketForm(forms.ModelForm):
class Meta:
model = Ticket
Expand All @@ -49,6 +57,30 @@ def __init__(self, user, *args, **kwargs):

attachments = MultipleFileField(required=False)

def clean_attachments(self):
files = self.cleaned_data.get('attachments')
if files:
for file in files:
# Check file size
if file.size > 1024 * 1024 * 5:
raise forms.ValidationError(
_('File size must be under 5MB.'))

# Check file type
uploaded_content_type = file.content_type
mg = magic.Magic(mime=True)
content_type = mg.from_buffer(file.read(1024))
file.seek(0)

if content_type != uploaded_content_type:
uploaded_content_type = content_type

if uploaded_content_type not in ATTACHMENT_CONTENT_TYPES:
raise forms.ValidationError(
_('File type not supported. Supported types are: .jpg, .png, .pdf'))

return files


class TemplateForm(forms.Form):

Expand Down

0 comments on commit f148c9f

Please sign in to comment.