By default, login_required, not adding a decorator everywhere

I am using Flask-HTTPAuth for authentication in my application. I have many views, and I do not want to add login_requiredto each of them. How can I make a default login?

from flask.ext.httpauth import HTTPBasicAuth
auth = HTTPBasicAuth()

@auth.verify_password
def verify_password(username, password):
    return username == '111' and password == '222'

@app.route('/')
@app.route('/home/')
@auth.login_required
def index():
    return 'Hello'

@app.route('/route2/')
def route2():
    return 'route2'

app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
+4
source share
1 answer

You can add a function before_requestthat requires a default input and create a simple decoder login_exemptfor several routes that do not require it.

Be sure to free the static files, otherwise they will not be downloaded for unauthenticated users.

Flask-HTTPAuth login_required require , , .

def login_exempt(f):
    f.login_exempt = True
    return f

# a dummy callable to execute the login_required logic
login_required_dummy_view = auth.login_required(lambda: None)

@app.before_request
def default_login_required():
    # exclude 404 errors and static routes
    # uses split to handle blueprint static routes as well
    if not request.endpoint or request.endpoint.rsplit('.', 1)[-1] == 'static':
        return

     view = current_app.view_functions[request.endpoint]

     if getattr(view, 'login_exempt', False):
         return

     return login_required_dummy_view()

# for example, the login page shouldn't require login
@app.route('/login', methods=['GET', 'POST'])
@login_exempt
def login():
    pass
+7

All Articles