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