Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-Principal Best Practice of Handling PermissionDenied Exception

I am new in writing flask and currently use flask-principal as my authorization mechanism. When a user tries to access a url without the required permission, flask-principal raises a PermissionDenied Exception.

It causes my system to throw a 500 internal server error.

How could I catch the specific exception and redirect user to a warning page instead? If you could share a code example, that will be very helpful.

like image 430
Theon Lin Avatar asked Nov 19 '13 10:11

Theon Lin


1 Answers

You can tell Flask-Principal that you want to raise a specific HTTP error code instead:

@app.route('/admin')
@admin_permission.require(http_exception=403)
def admin(request):
    # ...

Now flask.abort() will be called instead of raising PermissionDenied. For the 403 error code you can then register an error handler:

@app.errorhandler(403)
def page_not_found(e):
    session['redirected_from'] = request.url
    return redirect(url_for('users.login'))

where url_for('users.login') would return the route URL for a login page.

like image 82
Martijn Pieters Avatar answered Oct 26 '22 17:10

Martijn Pieters