16
votes

I want to restrict files to be available to logged in users, but otherwise return a 403 error or similar. For example a user should be able to view/download /static/data/example.csv only if they're logged in.

I know how to control the actual displaying of the files using Flask-Login if they're not logged in, but not how to block access to the file if they visit the link directly in their browser.

1
Not sure if this is the best way to do it, but I typically serve the files through Flask and make those files inaccessible via nginx (ie, don't put them in static folder). This way you control access with Flask-Login. This link may be helpful: flask.pocoo.org/docs/0.10/patterns/streaming - Gohn67
Thanks Gohn67, I hadn't thought of moving them out of the static folder until you mentioned this. - iamlolz
Depending on your privacy concerns, you can have nginx check for the presence of an authentication-related cookie and only serve the static files when found. - dirn
Thanks @dirn it's good to know I can handle it with nginx itself. - iamlolz

1 Answers

25
votes

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')