Best way to make Flask-Login's login_required the default


Like this question: Best way to make Django's login_required the default

I'm using Flask-Login's login_required decorator now. Is there anyway to make it the default behavior in Flask?

5/23/2017 11:55:06 AM

Accepted Answer

I did this in my instruments project. I use the before_request decorator:

def check_valid_login():
    login_valid = 'user' in session # or whatever you use to check valid login

    if (request.endpoint and 
        'static' not in request.endpoint and 
        not login_valid and 
        not getattr(app.view_functions[request.endpoint], 'is_public', False) ) :
        return render_template('login.html', next=request.endpoint)

and I then created an is_public() decorator for the few places that would need to be accessible without login:

def public_endpoint(function):
    function.is_public = True
    return function
11/19/2012 9:48:43 AM

If you are using blueprints and need to protect an entire blueprint with a login, you can make the entire before_request to require login.

This is what I use for my CMS blueprint:

def before_request():
    if g.user.role != ROLE_ADMIN:

If you need only to check if the user is logged in (and not if the user has privileges) you can simply pass the function

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow