pythonflaskflask-uploads

File download authentication in flask-uploads


Is there a possibility to force authentication of files served by Flask-Uploads or at least disable this route?

@uploads_mod.route('/<setname>/<path:filename>')
def uploaded_file(setname, filename):
    config = current_app.upload_set_config.get(setname)
    if config is None:
        abort(404)
    return send_from_directory(config.destination, filename)

It seems that any file that is uploaded can be downloaded by any (even not logged in) user.

Or only possibility is to use custom implementation as described in Flask Uploading Files?


Solution

  • It appears that Flask-Uploads does not offer a way to change how the route behaves. You do not need to give up Flask-Uploads though, you just need to replace the view with your own version.

    Assuming you're using Flask-Login and all you want is a simple login_required check, you can just replace the function in app.view_functions with the wrapped version.

    from flask_login import login_required
    
    app.view_functions['_uploads.uploaded_file'] = login_required(app.view_functions['_uploads.uploaded_file'])
    

    If you want something more complex, write your own view and replace with that instead. You can use app.endpoint to decorate the function instead of using app.view_functions directly.

    @app.endpoint('_uploads.uploaded_file')
    @login_required
    def my_uploaded_file(setname, filename):
        # do custom stuff