Prevent automatic login in after Flask-Security password reset

878 Views Asked by At

When a user resets their password with Flask-Security, they are automatically logged in. I want to prevent this automatic login and require the user to log in manually. How can I call logout_user after the password is reset, or otherwise prevent the user from being automatically logged in?

2

There are 2 best solutions below

0
On BEST ANSWER

Flask-Security's default reset_password view calls login_user then redirects. There is no option to skip login_user.

To override this, you need to write your own view and change the endpoint to point at it instead of the default view with app.endpoint. In this case, your view would copy the default code but remove the login_user line.

@app.endpoint(security.blueprint_name + '.reset_passowrd')
@anonymous_user_required
def reset_password(token):
    ########
    # copied code from flask_security.views omitted
    ########

    if form.validate_on_submit():
        after_this_request(_commit)
        update_password(user, form.password.data)
        do_flash(*get_message('PASSWORD_RESET'))
        ########
        # removed login_user call
        ########
        return redirect(get_url(_security.post_reset_view) or
                        get_url(_security.post_login_view))

    ########
    # copied code from flask_security.views omitted
    ########

All that said, I would advise against doing this. It messes with internal behavior, and doesn't really do anything for security. If the extension's code ever changes, your custom code won't reflect that. If the user has a reset token, they know the username and can set the password to whatever they want. Requiring them to then log in after that isn't useful, they already have the username and new password.

0
On

I know this is old but this method should work even if flask security updates the endpoints:

from flask_security.views import reset_password
from flask_security.utils import logout_user

@app.route('/admin/reset/<token>/', methods=['GET', 'POST'], endpoint="reset_password")
def custom_reset_password(token):
    flask_security_password_reset_view = reset_password(token)
    # Log the user out if they are logged in
    if current_user.is_authenticated:
        logout_user()
    return flask_security_password_reset_view

I found this useful because I have a custom 2FA implementation and the user should not be able to bypass that.