wbruntra February 2016

Creating restricted pages in google app engine

I'm having trouble creating admin pages on my Python Google App Engine site. I think the answer should be pretty straightforward, but honestly, I've been trying to understand how classes inheriting from other classes, or using functions to wrap other functions, and I just can't seem to get a good understanding of it.

Basically, my site has two kinds of pages: the main page, and then some pages that allow the user to perform admin actions. The main page can be seen by anyone without signing in. The other pages are for admins. The only users with accounts are admins, so I've set up webapp2 sessions, and as long as

self.sessions.get('username')

returns something that's enough to be allowed access to the other pages.

Here are my handlers:

class BaseHandler(webapp2.RequestHandler):
    def write(self, *a, **kw):
        self.response.out.write(*a, **kw)

    def render(self, template, **kw):
        self.response.out.write(render_str(template, **kw))

    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()

class MainHandler(BaseHandler):
    def get(self):
        animals = Animal.query().fetch(100)
        self.render('index.html',animals=animals)

class AdminHandler(BaseHandler):
    def get(self):
        if self.session.get('username'):
            self.render('admin.html')
        else:
            self.render('signin.html')

class ReorderHandler(BaseHandler):
    def get(self):
        self.render('reorder.html')
    def post(self):
        #Chang        

Answers


Brent Washburne February 2016

Here's a brute-force way to ensure a user is logged in for every page (except the login page), or it redirects them to the login page:

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

    if not self.session['username'] and self.request.get('path') != '/login':
        return redirect('/login')

A better way is to add this code to the top of every get() and put() routine:

def get(self):
    if not self.session['username']:
        return redirect('/login')

An even better way is to turn that code into a decorator so all you need to add is one line:

@require_login
def get(self):
    ....

Post Status

Asked in February 2016
Viewed 3,826 times
Voted 12
Answered 1 times

Search




Leave an answer