Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make sure a flask app has been authorized on all routes?

Tags:

python

rest

flask

I am, still, a n00b in Python and Flask. I am creating routes using flask for an API. I am integrating with the GitHub API using GitHub-Flask. Is there an easy and consistent way to check for a current access/request token before executing code for each route? Other than copy/pasting the same check all over the place, hopefully; which is currently what I am doing.

@app.route('/resource_1', methods=['GET'])
def get_resource_1():
  if not ACCESS_TOKEN:
    return redirect(url_for('login'))

  # ... do stuff for route

@app.route('/resource_2', methods=['GET'])
def get_resource_2():
  if not ACCESS_TOKEN:
    return redirect(url_for('login'))

  # ... do other stuff for this route

I imagine there is a much better way that this but I don't know how to find it.

like image 373
kalisjoshua Avatar asked Sep 01 '25 18:09

kalisjoshua


1 Answers

If you only want to protect certain routes, you can use a view decorator. This would look something like this:

  from functools import wraps
  from flask import g, request, redirect, url_for

    def login_required(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            if not ACCESS_TOKEN:
                return redirect(url_for('login'))
            return f(*args, **kwargs)
        return decorated_function

Then you decorate each resource like so:

@app.route('/resource_2', methods=['GET'])
@login_required
def get_resource_2():

View decorators are documented here: http://flask.pocoo.org/docs/0.10/patterns/viewdecorators/

If you want to protect absolutely every request then you can use the before_request handler on either the app or the blueprint level:

@app.before_request
def before_request():
    if not ACCESS_TOKEN:
        return redirect(url_for('login'))
like image 145
Robert Moskal Avatar answered Sep 04 '25 07:09

Robert Moskal