以编程方式启用或禁用@auth_basic() [英] Enable or disable @auth_basic() programmatically
问题描述
我正在尝试在程序中使用Bottle框架 @auth_basic(check_credentials)
装饰器,但是我希望能够基于用户在程序设置中做出的选择。
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.
我尝试在<$ c内执行 if
$ c> check_credentials 返回 True
如果设置为 False
但我仍然得到的登录弹出窗口始终返回 True
。我想完全不显示弹出窗口。
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---
推荐答案
HTTP身份验证正在弹出,因为您正在使用Bottle框架中的装饰器,这是默认行为链接。
HTTP Auth is popping because you are using the decorator from the bottle framework and this is a default behavior link.
您的设置实际上总是在做让所有人都参与进来,而不是禁用HTTP弹出窗口。您需要做的是实现另一个中间件来检查密码。
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)
这篇关于以编程方式启用或禁用@auth_basic()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!