2

Users of my Flask app login at https://example.com/login, but they can set a custom domain like http://customdomain.com

I'd like to be able to access Flask session variables when the user is visiting their custom domain so that I can present delete and modify user interface controls if the user is logged in.

Of course browsers prevent accessing cookies from domains other than where they were created.

Any thoughts or approaches to how I might work around this?

Raj
  • 3,791
  • 5
  • 43
  • 56
  • possible duplicate of [Cross-Domain Cookies](http://stackoverflow.com/questions/3342140/cross-domain-cookies) – Mark Hildreth Oct 30 '13 at 20:43
  • I read that question as well, but didn't think it was a duplicate in the least. They're talking about Java, the question is 3 years old, and things have changed considerably since then. CORS is a reality, I'm using Flask, etc, etc. – Raj Oct 30 '13 at 21:23

1 Answers1

0

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")
Raj
  • 3,791
  • 5
  • 43
  • 56