我正在尝试在程序中使用Bottle框架@auth_basic(check_credentials)
装饰器,但是我希望能够根据用户在程序设置中的选择启用或禁用它。
如果设置为if
,我尝试在check_credentials
内做一个True
以返回False
,但是我仍然会看到始终弹出的登录弹出窗口返回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---
答案 0 :(得分:1)
弹出HTTP身份验证,因为您正在使用Bottle框架中的装饰器,这是默认行为link。
设置的实际作用是始终允许所有人进入,而不是禁用HTTP弹出窗口。您需要做的是实现另一个“中间件”来检查密码。
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)