From f1cfaef5b0f358c94fe7f5e7c2eb5a6d261a85ae Mon Sep 17 00:00:00 2001 From: Jon Bergli Heier Date: Sat, 7 Dec 2019 11:14:01 +0100 Subject: Add max file size configuration This allows configuring max file sizes for both registered and anonymous users. For registered users the USER_FILE_SIZE_LIMIT is used, and ANONYMOUS_FILE_SIZE_LIMIT for anonymous users. If the size is not specified or None, the limit is not enforced. Setting the limit to 0 effectively disables uploads. --- fbin/file_storage/base.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'fbin/file_storage/base.py') diff --git a/fbin/file_storage/base.py b/fbin/file_storage/base.py index 9f09199..e2ca1a6 100644 --- a/fbin/file_storage/base.py +++ b/fbin/file_storage/base.py @@ -1,17 +1,26 @@ import datetime from .. import db +from .exceptions import * class BaseStorage: def __init__(self, app): self.app = app - def add_file(self, file_hash, filename, size, user=None, ip=None): + def verify_file(self, file): + user = file.user_id is not None + size_limit = self.app.config.get('USER_FILE_SIZE_LIMIT' if user else 'ANONYMOUS_FILE_SIZE_LIMIT') + if size_limit is not None and file.size > size_limit: + raise FileSizeError('The file size is too large (max {})'.format(db.File.pretty_size(size_limit))) + + def add_file(self, file_hash, filename, size, user=None, ip=None, verify=True): '''Adds the file to the database. Call from store_file after the file is successfully stored.''' with db.session_scope() as sess: f = db.File(file_hash, filename, size, datetime.datetime.utcnow(), user.id if user else None, ip) + # Raises on invalid files + self.verify_file(f) sess.add(f) sess.commit() sess.refresh(f) -- cgit v1.2.3