form: turn file type check into a hard check (#6134)

This commit is contained in:
Frédéric Péters 2014-12-12 14:39:31 +01:00
parent 476aa415d4
commit 4a91c263ea
1 changed files with 32 additions and 0 deletions

View File

@ -16,6 +16,7 @@
import base64
import cStringIO
import fnmatch
import mimetypes
import os
import re
@ -41,6 +42,11 @@ try:
except ImportError:
DNS = None
try:
import magic
except ImportError:
magic = None
import quixote
from quixote import get_publisher, get_request, get_response, get_session
@ -608,6 +614,32 @@ class FileWithPreviewWidget(CompositeWidget):
if file_size > self.max_file_size_bytes:
self.error = _('over file size limit (%s)') % self.max_file_size
if self.file_type:
# validate file type
accepted_file_types = []
for file_type in self.file_type:
accepted_file_types.extend(file_type.split(','))
if magic:
magic_object = magic.open(magic.MIME)
magic_object.load()
filetype = magic_object.file(self.value.fp.name).split(';')[0]
magic_object.close()
else:
filetype, encoding = mimetypes.guess_type(self.value.base_filename)
if not filetype:
filetype = 'application/octet-stream'
valid_file_type = False
for accepted_file_type in accepted_file_types:
# fnmatch is used to handle generic mimetypes, like
# image/*
if fnmatch.fnmatch(filetype, accepted_file_type):
valid_file_type = True
break
if not valid_file_type:
self.error = _('invalid file type')
class PicklableUpload(Upload):
def __getstate__(self):