Flask-Principal Best Practice of Handling PermissionDenied Exception
Asked Answered
P

1

9

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.

Pedestrian answered 19/11, 2013 at 10:36 Comment(0)
P
19

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.

Padua answered 19/11, 2013 at 11:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.