webpy and authentication

I’ve been using the development (0.2 version) of web.py to develop my own web gallery. So far it’s pretty awesome. I miss inheritance from Cheetah’s templates but otherwise everything has worked really well.

One thing that doesn’t really exist is support for authentication or sessions. Fortunately, sessions are pretty easy to add using flup, which is pretty much a requirement of using web.py.

So, with that in mind, here’s what I’m using for authentication:

login class, checks permissions

class login:
    def GET(self):
        i = web.input(uri = '/gallery/')
        session = web.ctx.environ['com.saddi.service.session'].session
        if session.get('auth', False):
            return web.seeother(i.uri)
        print templates.login(uri = i.uri)
    def POST(self):
        i = web.input(uri = '/gallery/', user = '', password = '')
        if validuser(i.user, i.password): # implement auth checking here
            session = web.ctx.environ['com.saddi.service.session'].session
            session['auth'] = 1
            return web.seeother(i.uri)
        print templates.login(uri = i.uri, user = i.user)

this class is a base class for any class that requires authentication:

class loginrequired:
    def _proxy_method(self, method):
        def proxy(*a, **kw):
            auth = self.session.get('auth', False)
            if not auth:
                return web.seeother('/gallery/login?uri=' + web.ctx.path)
            return method(*a, **kw)
        return proxy

    def __init__(self):
        self.session = web.ctx.environ['com.saddi.service.session'].session
        for method in ('GET','POST','PUT', 'DELETE'):
            if hasattr(self, method):
                meth = getattr(self, method)
                setattr(self, method, self._proxy_method(meth))

the _proxy_method is pretty similar to python decorators but: 1) doesn’t require 2.4 and 2) has access to the object context (self).

Finally, for any class that requires authentication:

class admingroup(loginrequired):
    def GET(self, gallery = ''):
        print templates.admingroup(gallery)
This entry was posted in tech. Bookmark the permalink.

One Response to webpy and authentication

  1. a says:

    why dou use
    self.session = web.ctx.environ['com.saddi.service.session'].session

    for ur website
    shudnt u use
    web.ctx.environ['meat.net'].session

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>