Enable or disable @auth_basic() programmatically

百般思念 提交于 2019-12-13 02:36:53

问题


I'm trying to use the Bottle framework @auth_basic(check_credentials) decorator within my program but I would like to be able to enable it or disable it based on a choice made by the user in program settings.

I've tried to do a if inside the check_credentials to return True if the setting is False but I'm still getting the login popup which is always returning True. I would like to not get the popup at all.

Any idea how I could achieve that?

def check_credentials(user, pw):
    if auth_enabled == True:
        username = "test"
        password = "test"
        if pw == password and user == username:
            return True
        return False
    else:
        return True

@route('/')
@auth_basic(check_credentials)
def root():
    # ---page content---

回答1:


HTTP Auth is popping because you are using the decorator from the bottle framework and this is a default behavior link.

What your setting actually do is always letting everyone in, not to disable the HTTP pop up. What you need to do is to implement another "middleware" that checks for the password.

from bottle import route, Response, run, HTTPError, request

auth_enabled = True


def custom_auth_basic(check, realm="private", text="Access denied"):
    ''' Callback decorator to require HTTP auth (basic).
        TODO: Add route(check_auth=...) parameter. '''
    def decorator(func):
        def wrapper(*a, **ka):
            if auth_enabled:
                user, password = request.auth or (None, None)
                if user is None or not check(user, password):
                    err = HTTPError(401, text)
                    err.add_header('WWW-Authenticate', 'Basic realm="%s"' % realm)
                    return err
                return func(*a, **ka)
            else:
                return func(*a, **ka)

        return wrapper
    return decorator


def check_credentials(user, pw):
    if auth_enabled:
        username = "test"
        password = "test"
        if pw == password and user == username:
            return True
        return False
    else:
        return True


@route('/')
@custom_auth_basic(check_credentials)
def root():
    return Response("Test")


run(host='localhost', port=8080)


来源:https://stackoverflow.com/questions/51630946/enable-or-disable-auth-basic-programmatically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!