Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share sessions between modules on a Google App Engine Python application?

I'm trying to make a basic app on Google App Engine with two modules using Google App Engine Modules(https://developers.google.com/appengine/docs/python/modules/) and They share session information between the modules:

Modules:

  • Module 1 - Login Page: a basic page with a login form where if is a valid user I create a session and then the user is redirected to the dashboard page(Module 2)
  • Module 2 - Dashboard Page: a page that show a message if the module can read the data in the session variable

The problem is that in the dashboard module the session data created in the Login Page(module 1) does not exist.

Is it possible access the sessions data between two o more modules in Google App Engine?

Source:

baseHandler.py

import webapp2
from webapp2_extras import sessions

class BaseHandler(webapp2.RequestHandler):

    def render_template(self, view_filename, params=None):
        params = {}
        path = os.path.join(os.path.dirname(__file__), 'views', view_filename)
        self.response.out.write(template.render(path, params))

    def display_message(self, message):
        """Utility function to display a template with a simple message."""
        params = {}
        self.render_template('message.html', params)

    def dispatch(self):
        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)

        try:
            # Dispatch the request.
            webapp2.RequestHandler.dispatch(self)
        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)

    @webapp2.cached_property
    def session(self):
        # Returns a session using the default cookie key.
        return self.session_store.get_session()

Module 1(Signin) main.py

from google.appengine.ext import ndb
import webapp2
from webapp2_extras.security import hash_password

import logging
import os
import sys
import jinja2

from src.basehandler import BaseHandler
from src.user import User

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape']
)

class MainPage(BaseHandler):

    def get(self):
        template_values = {}
        template = JINJA_ENVIRONMENT.get_template('templates/index.html')
        self.response.write( template.render( template_values ) )


    def post(self):
        email_address = self.request.get('input-email')
        password = self.request.get('input-password')

        password = hash_password( password, 'sha1', salt=None, pepper=None )

        qry = User.query(
            ndb.AND(User.email_address == email_address,
                    User.password == password
            )
        ).fetch()

        if qry:
            self.session['loggedin'] = True
            self.redirect('http://dashboard.myURL.appspot.com/')

        else:
            self.redirect('/?error=invaliduser')

config = {}
config['webapp2_extras.sessions'] = {
    'secret_key': 'my-super-secret-key',
}

app = webapp2.WSGIApplication([
    ('/', MainPage)
], debug=True, config=config )

Module 2(Dashboard) main.py

from google.appengine.ext import ndb
import webapp2

import logging
import os
import sys
import jinja2

from src.basehandler import BaseHandler
from src.user import User

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape']
)

class Main(BaseHandler):

    def get(self):
        msg = ''

        if not self.session.get('loggedin'):
            msg = 'There is not session'

        else:
            msg = 'There is a session'

        template_values = { 'msg': msg }
        template = JINJA_ENVIRONMENT.get_template('templates/index.html')
        self.response.write( template.render( template_values ) )

config = {}
config['webapp2_extras.sessions'] = {
    'secret_key': 'my-super-secret-key',
}

app = webapp2.WSGIApplication([
    ('/', Main)
], debug=True, config=config )

Any help is welcome, sorry if something is misspelled

like image 666
Wilcho Avatar asked Jul 17 '14 18:07

Wilcho


1 Answers

By default webapp2_extra.sessions uses cooki-based sessions. These will be tied to a specific domain. Your modules are probably at module1.yourapp.appspot.com and module2.yourapp.appspot.com (a guess). The second module won't be able to see the cookies set by the first module.

In your config try setting the domain for the cookie.

config['webapp2_extras.sessions'] = {
    'secret_key': 'my-super-secret-key',
     cookie_args': { 
         'domain' : "yourapp.appspot.com"
}

The docs say:

 - domain: Domain of the cookie. To work accross subdomains the
   domain must be set to the main domain with a preceding dot, e.g.,
   cookies set for `.mydomain.org` will work in `foo.mydomain.org` and
   `bar.mydomain.org`. Default is None, which means that cookies will
   only work for the current subdomain.

from: https://code.google.com/p/webapp-improved/source/browse/webapp2_extras/sessions.py

Or you could also use one of the other backends like memcache or datastore. This is preferred if your sessions contain sensitive info.

like image 138
SkyeC Avatar answered Nov 15 '22 09:11

SkyeC