以编程方式启用或禁用 @auth_basic()

Enable or disable @auth_basic() programmatically

我正在尝试在我的程序中使用 Bottle 框架 @auth_basic(check_credentials) 装饰器,但我希望能够根据用户在程序设置中所做的选择启用或禁用它。

如果设置为 False,我尝试在 check_credentials 到 return True 中执行 if,但我仍然总是 returning True 的登录弹出窗口。我不想弹出窗口。

知道如何实现吗?

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---

HTTP Auth 正在弹出,因为您正在使用 bottle 框架中的装饰器,这是默认行为 link

您的设置实际上是始终让每个人都进入,而不是禁用 HTTP 弹出窗口。您需要做的是实现另一个 "middleware" 来检查密码。

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)