即使在Flask中关闭浏览器后,我如何将一个会话变量存储一段时间



我使用的是Flask Login的函数Login((,其中member=True。

这很好用。但最近我实现了双因素身份验证,用户必须下载验证器应用程序才能登录。

我创建了自己的@tfa_required装饰器,在用户启用TFA的情况下使用@login_required。我跟踪登录状态的方法是使用一个名为auth_level的会话变量来了解用户是否使用TFA成功登录。(附代码片段(。

假设用户登录到一个浏览器,然后关闭了它。他仍然会登录(因为他是在记住=True的情况下登录的(,但他必须再次输入TFA(auth_level=1——意味着TFA还没有成功——现在而不是auth_level=2(。

我真正想要的是,只要Flask Login记得用户登录,即使在关闭浏览器后,也要存储auth_level会话变量。

据我所知,Flask Login使用不同的会话来存储与登录相关的变量,这样用户在一段时间内仍然可以登录。

如何让客户端即使在关闭浏览器后也能记住auth_level

谢谢。

# Decorator for TFA-required views
def tfa_login_required(f):
"""Implement additional TFA checking, on top of login_required.
TFA is only checked if it has been activated for the user.
"""
@wraps(f)
@login_required
def decorated_function(*args, **kwargs):
# if the user is authenticated and has tfa enabled but not tfa passed
if (
current_user.tfa_enabled
and session.get('auth_level') != 2
):
return redirect(url_for('auth.login_view'))
# if authenticated proceed normally
else:
return f(*args, **kwargs)
return decorated_function

使用login_required而不使用tfa_required的示例:

@auth.route('/logout/')
@login_required
def logout():
logout_user()
session['auth_level'] = 0
session.modified = True
return redirect(url_for('main.home'))

使用两者的示例,tfa_required AND login_rerequired:

@main.route('/some_route/', methods=['GET'])
@tfa_login_required
def some_route():
do_some_work_that_requires_full_authentication()

您可能正在寻找this

默认情况下,如果选项卡关闭,Flask将删除所有会话数据。为了使其永久化,可以这样做:

@app.before_request
def set_permanent_session():
session.permanent = True

我最终使用了Flask登录cookie本身,将变量包含在Flask登录cookie中。供参考,这里是代码:

from flask_login import (
....
COOKIE_DURATION,
COOKIE_SECURE,
COOKIE_HTTPONLY,
encode_cookie,
)

在view函数中,我不返回url_for(...),而是使用make_response()创建一个响应对象,并使用以下命令设置响应cookie:

response = make_response(redirect(url_for('...')))
# Setting cookie similar to Flask Login way of setting its cookies
duration = current_app.config.get('REMEMBER_COOKIE_DURATION', COOKIE_DURATION)
secure = current_app.config.get('REMEMBER_COOKIE_SECURE', COOKIE_SECURE)
httponly = current_app.config.get('REMEMBER_COOKIE_HTTPONLY', COOKIE_HTTPONLY)
expires = duration + datetime.utcnow()
# encode additional data to ensure that the user cannot simply use the value
# from the remember cookie
data = encode_cookie(str(session['_user_id']) + '_cookie_variable')
response.set_cookie(
'cookie_variable',
value=data,
expires=expires,
secure=secure,
httponly=httponly
)
return response

相关内容

最新更新