Restrict static file access to logged in users

Flask adds a static route to serve static files. When you’re in production, you typically “short circuit” this route so that Nginx serves the files before the request ever gets to your app. Instead of adding this “short circuit”, leave it out and let Flask handle the requests. Overwrite the static route with one that is wrapped by Flask-Login’s login_required.

from flask_login import login_required

app.view_functions['static'] = login_required(app.send_static_file)

This is typically overkill though, since you want truly static files to be served no matter what so that pages look right to non-logged in users (otherwise the CSS wouldn’t even be sent for the login page). Instead, “short circuit” the static folder to be served by Nginx, and define a route that will serve protected files from some other directory, such as the instance folder. See flask.send_from_directory.

import os
from flask import send_from_directory
from flask_login import login_required

@app.route('/protected/<path:filename>')
@login_required
def protected(filename):
    return send_from_directory(
        os.path.join(app.instance_path, 'protected'),
        filename
    )

This will serve files from the directory “protected” in the instance folder to logged in users only. Other restrictions could also be added, such as only allowing certain users access to certain files. Similar to the static path, you can generate a url to a file with:

url_for('protected', filename="data/example.csv")

Leave a Comment