Correct way to protect flask control

flask-sentinel creates a route to the control UI using app.add_url_rule . Wanting to enforce some access control rules, I wrapped it like this:

from flask.ext import sentinel

def requires_auth(fn):
    @wraps(fn)
    def decorated(*args, **kwargs):
        roles = []
        if 'user' in session and 'roles' in session['user']:
            roles = session['user']['roles']

        if 'admin' not in roles:
            flash("Not enough power")
            return redirect('/')

        return fn(*args, **kwargs)
    return decorated

sentinel.views.management = requires_auth(sentinel.views.management)
sentinel.ResourceOwnerPasswordCredentials(app)

      

The question is, is this really the way or is there a better way?

EDIT: Realized that my question was quite abstract, and in fact almost a flask instead of a sentry. Guess what I wanted to ask, "Is there an even more declarative way of applying security restrictions to paths in Flask, instead of logging each route to every registered route?" After doing a little research, this seems to provide the flexible security controls I was looking for.

from flask import Flask, request
app = Flask('bla')

PATH_ROLES = {
    '/admin/.*': ['admin']
}

@app.before_request
def before_request():
    try:
        rule = next(x for x in PATH_ROLES if re.match(x, request.path))
        print "path requires: ", PATH_ROLES[rule]
    except StopIteration: pass

      

+3


source to share


1 answer


With a quick glance, I would say your approach sounds good. You are basically applying the generic Flask pattern of wrapping a view with a decorator .



+2


source







All Articles