Skip to content
This repository has been archived by the owner on Sep 5, 2019. It is now read-only.

Commit

Permalink
Limits the size of uploaded files.
Browse files Browse the repository at this point in the history
  • Loading branch information
Denis Krienbühl committed Jun 1, 2015
1 parent 45842b5 commit d549995
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
3 changes: 3 additions & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ Changelog
Unreleased
~~~~~~~~~~

- Limits the size of uploaded files.
[href]

- No longer stores the csrf_token with the form submission.
[href]

Expand Down
19 changes: 17 additions & 2 deletions onegov/form/parser/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@
time,
)
from onegov.form.utils import label_to_field_id
from onegov.form.validators import Stdnum, ExpectedExtensions
from onegov.form.validators import Stdnum, ExpectedExtensions, FileSizeLimit
from wtforms import (
FileField,
PasswordField,
Expand Down Expand Up @@ -313,6 +313,18 @@
])


# increasing the default filesize is *strongly discouarged*, as we are not
# storing those files efficently yet -> they need to fit in memory
#
# if this value should be higher, we need to either:
# * store the files outside the database
# * store the files in a separate table where they are not read into memory
# as frequently as they are now
#
MEGABYTE = 1024 ** 2
DEFAULT_UPLOAD_LIMIT = 5 * MEGABYTE


class CustomLoader(yaml.SafeLoader):
""" Extends the default yaml loader with customized constructors. """

Expand Down Expand Up @@ -501,7 +513,10 @@ def handle_block(builder, block, dependency=None):
label=identifier.label,
dependency=dependency,
required=identifier.required,
validators=[ExpectedExtensions(field.extensions)]
validators=[
ExpectedExtensions(field.extensions),
FileSizeLimit(DEFAULT_UPLOAD_LIMIT)
]
)
elif field.type == 'radio':
choices = [(c.label, c.label) for c in field.choices]
Expand Down
15 changes: 15 additions & 0 deletions onegov/form/validators.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import importlib
import os

from stdnum.exceptions import ValidationError as StdnumValidationError
from wtforms import ValidationError
Expand Down Expand Up @@ -45,3 +46,17 @@ def __init__(self, extensions):
def __call__(self, form, field):
if not field.data.filename.endswith(self.extensions):
raise ValidationError(field.gettext(u'Invalid input.'))


class FileSizeLimit(object):
""" Makes sure an uploaded file is not bigger than the given number of
bytes.
"""

def __init__(self, max_bytes):
self.max_bytes = max_bytes

def __call__(self, form, field):
if os.fstat(field.data.file.fileno()).st_size > self.max_bytes:
raise ValidationError(field.gettext(u'Invalid input.'))

0 comments on commit d549995

Please sign in to comment.