Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a python decorator function in Flask with arguments (for authorization)

I used a flask snippet for my flask-login that checks that a user is logged in:

from functools import wraps

def logged_in(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if session.get('logged_in') is not None:
            return f(*args, **kwargs)
        else:
            flash('Please log in first.', 'error')
            return redirect(url_for('login'))
    return decorated_function

And I decorate views like so:

@app.route('/secrets', methods=['GET', 'POST'])
@logged_in
def secrets():
    error = None

I'd like to do something similar for authorization, too. Right now, I have many views to check that a user owns a resource, let's say the hotdogs resource.

If the logged_in user is the owner of that particular hotdog, he can edit and manage his hotdogs. If he isn't, I kick him out to the unauthorized screen.

@app.route('/<hotdog>/addmustard/',methods=["GET"])
@logged_in
def addmustard(hotdog):
    if not (authorizeowner(hotdog)):
        return redirect(url_for('unauthorized'))
    do_stuff()

authorizeowner() takes a hotdog as input and checks that the recorded hotdog owner matches the owner name listed in the session variable.

I tried making a owns_hotdog wrapper/decorator function similar to my logged in one, but it complained that it didn't accept arguments. How can I achieve something similar? Something like...

def owns_hotdog(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not authorizeowner(hotdog):
            return f(*args, **kwargs)
        else:
            flash('Please log in first.', 'error')
            return redirect(url_for('login'))
    return decorated_function

From the error message, decorator seems not to be receiving the hotdog argument that Flask views have access to from the variable in the route. My hope is for something like...

@app.route('/<hotdog>/addmustard/',methods=["GET"])
@logged_in
@owns_hotdog(hotdog)
def addmustard(hotdog):
    do_stuff()

Everything works with my current authorizeowner(hotdog) function, but it just seems cleaner to have this in place as a wrapper on top of my route, rather than as the first line inside the route.

Some other notes:

  • I know that Flask-Security and Flask-Principal can manage authorization for me. Unfortunately, I'm using an unsupported database back-end and am unable to use these extensions. So, I'm forced to do authentication without them.
  • If you see any glaring holes in doing authorization this way, please let me know!
like image 880
Mittenchops Avatar asked Dec 15 '12 22:12

Mittenchops


People also ask

Can Python decorator take argument?

Implementing Decorator Arguments You may expect that decorator arguments are somehow passed into the function along with this f argument, but sadly Python always passes the decorated function as a single argument to the decorator function.

How do you make a decorator in a Flask?

An example of a Flask decorator that you have probably used is the @app. route('/') for defining routes. When displaying the output to a browser, this decorator converts a function into a route that can be accessed by the browser without having to explicitly invoke the function in the program.

How do Flask applications use function decorators?

Typically, decorators run some code before executing the sub-function. For example, if you want to add authentication to certain endpoints of your Flask app, you can use decorators. The decorators check to make sure a user is authenticated to use a resource before the actual code of that resource executes.


1 Answers

Here's how to do it:

from functools import update_wrapper  def owns_hotdog(hotdog):     def decorator(fn):         def wrapped_function(*args, **kwargs):             # First check if user is authenticated.             if not logged_in():                 return redirect(url_for('login'))             # For authorization error it is better to return status code 403             # and handle it in errorhandler separately, because the user could             # be already authenticated, but lack the privileges.             if not authorizeowner(hotdog):                 abort(403)             return fn(*args, **kwargs)         return update_wrapper(wrapped_function, fn)     return decorator  @app.errorhandler(403) def forbidden_403(exception):     return 'No hotdogs for you!', 403 

When decorator takes arguments, it's not really a decorator, but a factory function which returns the real decorator.

But if I were you, I would use Flask-Login for authentication and augment it with custom decorators and functions as yours to handle authorization.

I looked into Flask-Principal, but found it overly complicated for my tastes. Haven't checked Flask-Security, but I believe it uses Flask-Principal for authorization. Overall I think that Flask-Login with some custom code is enough most of the time.

like image 197
Audrius Kažukauskas Avatar answered Oct 16 '22 07:10

Audrius Kažukauskas