flask-security ajax logout causes session errors

601 Views Asked by At

When I post to a flask endpoint:

@app.route('/api/v1/logout', methods=['POST','GET'])
def logout():
    logout_user()
     return jsonify(status=200, message='User has been successfully logged out.')

I get an error when I try to log in the next time

InvalidRequestError: Object '<User at 0x7f09b4831c90>' is already attached to session '1' (this is '4')

I was wondering how to logout and in safely using ajax.

Edit- angularjs login controller:

LoginController: function ($scope, $http, authService, $location) {
    $scope.submit = function() {
      console.log('in logincontroller')
      $http.defaults.headers.post['X-CSRFToken'] = csrf_token;
      $http.defaults.headers.common['Content-Type'] = 'application/json'
      //debugger;
      $http.post(
    '/login',
      JSON.stringify({ email: $scope.email, password: $scope.password })
      ).success(
    function(data) {
      if (data.meta){
        var status_code = data.meta.code;
      }
      else{
        var status_code = data.status;
      }
      if (status_code == 200){        
        $.cookie('email', $scope.email, { expires: 7 });
        $.cookie('auth_token', data.authentication_token, { expires: 7 });
        $http.defaults.headers.common['Authentication-Token'] = data.authentication_token;
        authService.loginConfirmed();
        $location.path("/dashboard");
      }
      else{
     //form stuff
      }
    }
    ).error(
    function(data) {
      alert('LoginController submit error');
      $scope.errorMsg = data.reason;
      //debugger;
    }
      );
    };
  }
2

There are 2 best solutions below

4
On

I guess You have to redirect at the end to get out of the existing session

@app.route('/logout')
def logout():
    # remove the username from the session if it's there
    session.pop('username', None)
    return redirect(url_for('index'))
1
On

You are doing it very wrong.

Since you didn't provide your login method, I guess from the error log that you were storing a User model in the session. This is totally wrong.

My suggestion is that you store your user's id in the session. e.g.

def login_user(user):
    session['user_id'] = user.id

If you need to know the current user:

def get_current_user():
    return User.get(session['user_id'])

Ask the right question, so that people can help you.