Share Sessions between Google Cloud Endpoints and webapp2

There are some cases where you want to be able to use the Google Cloud Endpoints feature on App Engine but you would also like to be able to access your session data that is managed by webapp2 backed by either memcache or the NDB datastore. Well you can! And here’s how.

Imports

You’ll need to import the following modules in your API script. Note that I’m assuming that you’re using NDB backed sessions just like me. If you’re using session_memcache instead of session_ndb this won’t work.

I’m also using werkzeug because it makes it easier to work with the cookie data.

from webapp2_extras import sessions_ndb
import webapp2_extras
import werkzeug
import hashlib
import hmac

Helper Methods

Here are 2 helper methods. One verifies the cookie signature to make sure it’s not been tampered with. You want to make sure that COOKIE_SECRET_KEY is set to the value of secret_key under webapp2_extras.sessions from your webapp2 config.

def compare_hashes(a, b):
    """Checks if two hash strings are identical.

    The intention is to make the running time be less dependant on the size of
    the string.

    :param a:
        String 1.
    :param b:
        String 2.
    :returns:
        True if both strings are equal, False otherwise.
    """
    if len(a) != len(b):
        return False

    result = 0
    for x, y in zip(a, b):
        result |= ord(x) ^ ord(y)

    return result == 0

This is what does all the magic.

def get_current_session(request_state):
    cookies = werkzeug.http.parse_cookie(request_state.headers.get('Cookie'))
    sess_cookie = cookies.get('mc_session')
    parts = sess_cookie.split('|')
    if len(parts) != 3:
        logging.error('Cookie does not have 3 parts')
        return False

    signature = hmac.new(COOKIE_SECRET_KEY, digestmod=hashlib.sha1)
    signature.update('|'.join(parts))
    sig_hex = signature.hexdigest()
    if compare_hashes(sig_hex, parts[2]):
        logging.error('Cookie signature mismatch!')
        return False

    cookie_data = webapp2_extras.json.b64decode(parts[0])
    return sessions_ndb.Session.get_by_sid(cookie_data['_sid'])

Now in your API method you would simply add the following line:

session = get_current_session(self.request_state)

Now session will contain all your session data. You can for example do session.get(‘mystuff’).

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *