3

I am using permanent_session_lifetime to expire the session of the user after some period of inactivity. The problem is that, this request is made through ajax, so i can't redirect in ajax context with the normal behavior of the flask.

http://xxxx/login?next=%2Fusers%2Fajax_step1

Instead of this, I want to redirect to my logout route in the before_request, if the flask session expire. How can i do that?


@mod.before_request
def make_session_permanent(): 
    session.modified = True
    session.permanent = True
    app.permanent_session_lifetime = timedelta(minutes=10)

@mod.route('/logout')
@login_required
def logout():
    logout_user()
    session.clear()
    flash(gettext(u'You have been logged out.'))
    return redirect(url_for('auth.login'))
anvd
  • 3,997
  • 19
  • 65
  • 126
  • 1
    Can you modify your AJAX to look for some indication of logout (maybe a status code, or use a JSON message) and then have it redirect to the proper page? – swehren May 20 '15 at 19:57

1 Answers1

1

If you want to use the before_request approach, then check for the session's validity there and return a redirect as needed:

@mod.before_request
def make_session_permanent():
    if session_is_invalid(session):
        return redirect(url_for('logout'))

def session_is_invalid(ses):
    # return your qualifier

Otherwise, swehren's comment is a good idea - instead of relying on the background to redirect the next call, have the Ajax call in the front redirect based on the return valid of the Ajax call:

$.ajax({
    type: "POST",
    url: "{{ url_for('login') }}",
    success: function(data) {
        // redirect if the data contained a qualifier for an expired session
    }
});
Celeo
  • 5,583
  • 8
  • 39
  • 41