Here's what I did; seems to work well. I make an AJAX JSONP call to the server using withCredentials
set to true
. The server gets the session cookie and tells the client whether the user is logged in or not. Based on the response I can show additional user interface elements to the user.
<script>
$(".logged_in").hide();
request = $.ajax({
url: "http://example.com/ping/",
type: "GET",
dataType: "jsonp",
xhrFields: {
withCredentials: true
}
});
request.done(function (response, textStatus, jqXHR){
// log a message to the console
if (response['logged_in'])
{
$(".logged_in").show();
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error("The following error occurred: " + textStatus, errorThrown);
console.log("jqXHR: " + JSON.stringify(jqXHR))
});
</script>
Server code:
def jsonp(func):
"""Wraps JSONified output for JSONP requests."""
@wraps(func)
def decorated_function(*args, **kwargs):
callback = request.args.get('callback', False)
if callback:
data = str(func(*args, **kwargs).data)
content = str(callback) + '(' + data + ')'
mimetype = 'application/javascript'
return current_app.response_class(content, mimetype=mimetype)
else:
return func(*args, **kwargs)
return decorated_function
@app.route('/ping/')
@jsonp
def ping():
if 'user_id' in session:
print "session ping: %s" % session
return jsonify(logged_in='true')
else:
print "session ping: not logged in"
return jsonify(logged_in="false")