Session expires in flask in ajax context
I am using permanent_session_lifetime
to expire a user session after a period of inactivity. The problem is this request is done via ajax, so I cannot redirect in ajax context with normal flask behavior.
http://xxxx/login?next=%2Fusers%2Fajax_step1
Instead, I want to redirect to my route logout
in before_request
if the flask session expires. How can i do this?
@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'))
source to share
If you want to use the approach before_request
then check for the existence of a session and return a redirect if 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, ask for an Ajax call in the forward redirect based on a return valid for the Ajax call:
$.ajax({
type: "POST",
url: "{{ url_for('login') }}",
success: function(data) {
// redirect if the data contained a qualifier for an expired session
}
});
source to share