这种从FlaskLogin使用当前用户的方式安全吗?

2024-06-10 01:47:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难理解Flask登录库中的当前用户是如何工作的。例如,当两个用户同时访问同一个路由并使用其功能时,我调用多个模块,这些模块也将当前用户用作导入。我将用一些代码详细说明:

我有一个叫做更新账户的路线(我删除了一些部分,因为它们与我的问题无关):

@users.route('/account/user/<username>/update', methods=['GET', 'POST'])
def update_account(username):
    update_account_form = UpdateForm()
    if update_account_form.validate_on_submit():
        #here we handle updating from another module
        if AccountManager.update_account(update_account_form): #retuns True if no errors has occured
            flash('Your account has been successfully updated', "success")
            return redirect(url_for('users.update_account', username=current_user.username))
        flash('Your client matched max requests', "warning")
        return redirect(url_for('users.update_account', username=current_user.username))
    return render_template('account/update.html', update_form=update_account_form)

我的问题是关于我称之为AccountManager.update_account(update_account_form)的部分,因为我没有传递任何当前用户数据,而是在该模块中导入当前用户,这就是我获取数据的方式。下面是我如何实现的:

   from flask_login import login_user, current_user 
 
   class AccountManager:
        @staticmethod
        def update_account(account_form):
            if current_user.request_counter >= 5:
                return False
            current_user.username = account_form.username.data.strip()
            current_user.email = account_form.email.data.strip()
            if account_form.change_password.data:
                current_user.password = bcrypt.generate_password_hash(account_form.password.data).decode('utf-8')
            db.session.commit()
            return True

我的问题就在这里。这安全吗?我应该将当前用户作为参数传递,而不是在此处导入它吗?因为如果出现另一个请求,当前用户可能会更改,而此方法将更改其他人的数据

谢谢你抽出时间


Tags: 模块用户formdatareturnifdefusername