简体   繁体   中英

is this way of using current_user from Flask-Login safe?

I'm having trouble with understanding how current_user from Flask-Login library works. For example when two users access the same route at the same time and withing its function I call multiple modules that also use the current_user as an import. I will elaborate more with some code:

I have this route called update_account(I removed some parts because they are not related to my question):

@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)

My question is about the part I call AccountManager.update_account(update_account_form) because im not passing any of current_users data instead i'm importing current_user in that module as well and thats how I get the data. Below is how I implemented that:

   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

My question is right here. Is this safe? Should I pass current_user as a parameter instead of importing it here? because maybe if another request comes the current_user changes and this method will change someone else data.

thanks for your time.

What you are doing is fine.

current_user is dependent on the request context so you will not get a different user just because another user's request came in before you finished processing the first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM