Search code examples
pythonflaskflask-security

Prevent automatic login in after Flask-Security password reset


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?


Solution

  • 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.