[英]Show basic auth popup if user is not logged in
我有几个文件可以在我的网站上下载。 HTML内容引用此方法:
from flask_httpauth import HTTPBasicAuth
auth = HTTPBasicAuth()
...
@app.route('/customer_section/download/<product_id>')
@login_required
def customer_download_file(product_id):
# get the company the currently logged in user belongs to
user_company = current_user.company
# get the product entity
product = Product.query.filter_by(id=product_id).first_or_404()
# now get the company, the product belongs to
product_company = product.project.owner
if current_user.is_admin or (not current_user.is_admin and product_company.id == user_company.id):
print("Splitting Path %s to folder and filename..." % product.path)
# Split the path to folder and filename
folder, filename = os.path.split(product.path)
return send_from_directory(folder, filename, mimetype="application/octet-stream", as_attachment=True)
else:
# Unauthorized
abort(401)
当用户在我的登录视图中通过flask_login登录时,此功能非常有用。 因此,用户通过我的登录视图登录,然后以某种方式浏览我的网站,然后单击下载链接以下载文件。
但是,如果用户尝试直接下载文件怎么办? 然后,我想向用户显示一个弹出窗口,以便用户可以输入其凭据并可以下载文件。
这可能吗?
抱歉,我的描述不够清楚:当用户调用我的下载方法时,我没有试图显示我的自定义弹出视图。 如果非登录用户尝试调用该特定URL,我希望显示默认的(特定于浏览器的)基本身份验证弹出窗口。 好像我有一个限制性的.htaccess文件,可以确保只有授权用户才能继续。 如果用户通过我的网页到达相同的URL(登录后,此方法仅返回文件流)。
好的,在阅读了此链接后,我像这样解决了它:
def get_db_user(username):
user = User.query.filter_by(username=username).first()
return user
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
if current_user.is_authenticated:
return True
user = get_db_user(username)
if not user or not user.check_password(password):
return False
else:
return True
@login.unauthorized_handler
def handle_unauthorized_callback():
page_to_load = request.path
print("Tried to access page: %s" % page_to_load)
# this regex match checks whether a specific url was called
if is_file_download_url_pattern.match(page_to_load):
basic_auth = request.authorization
if not basic_auth or not check_auth(basic_auth.username, basic_auth.password):
return authenticate()
else:
user = get_db_user(basic_auth.username)
login_user(user, False)
# extract product id
product_id = re.search(product_id_pattern, page_to_load).group()
return customer_download_file(int(product_id))
else:
return redirect(url_for('login'))
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'}
)
我不知道这是否是一个优雅的解决方案,但至少现在可以解决我的问题。 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.