Issue #366 resolved

Recipe: non-decorator version for CP 2.1

Anonymous created an issue

The version of on the wiki is for CP 2.0

Below is a version that works with CP 2.1

Also, the description on the Recipies page says its for Python 2.4 with decorators, but this version works with 2.3, no decorators, so that description is misleading.


import cherrypy

class Login: def check(cls, fn): def _check(self, *args, kwargs): if cherrypy.session.get('userid', None): # User is logged in; allow access return fn(self, *args, kwargs) else: # User isn't logged in yet.

            # See if the user just tried to log in
                submit = kwargs['login']
                email = kwargs['loginEmail']
                password = kwargs['loginPassword']
            except KeyError:
                # No, this wasn't a login attempt.  Send the user to
                # the login "page".
                return self.loginPage(cherrypy.request.path)

            # Now look up the user id by the email and password
            userid = self.getUserId(email, password)
            if userid is None:
                # Bad login attempt
                return self.loginPage(cherrypy.request.path, 'Invalid username or password.')
            # User is now logged in, so retain the userid and show the content
            cherrypy.session['userid'] = userid
            return fn(self, *args, **kwargs)
    return _check
check = classmethod(check)

def getUserId(self, email, password):
    '''Simple function to look up a user id from email and password.
    Naturally, this would be stored in a database rather than
    hardcoded, and the password would be stored in a hashed format
    rather than in cleartext.

    Returns the userid on success, or None on failure.

    accounts = {('', 'foo'): 'tim'}

    return accounts.get((email,password), None)

def loginPage(self, targetPage, message=None):
    '''Return a login "pagelet" that replaces the regular content if
    the user is not logged in.'''
    result = []
    result.append('<h1>Sitename Login</h1>')
    if message is not None:
        result.append('<p>%s</p>' % message)
    result.append('<form action=%s method=post>' % targetPage)
    result.append('<p>Email Address: <input type=text name="loginEmail"></p>')
    result.append('<p>Password: <input type=password name="loginPassword"></p>')
    result.append('<p><input type="submit" name="login" value="Log In"></p>')
    return '\n'.join(result)

def logOut(self):
    '''Log Out.'''
        del cherrypy.session['userid']
    except KeyError:
        #Not logged in, nothing to do.
    return 'You are logged out.' + self.index() = True

class Page(Login): def index(self): return '''<h1>SiteName</h1> <h2>Home Page</h2> <p><a href="public">Public Page</a></p> <p><a href="private">Private Page</a> <i>(registered users only)</i></p> ''' = True

def public(self):
    return '''<h1>SiteName</h1>
    <h2>Public Page</h2>
    <p><a href="/">Go back home</a></p>''' = True

def private(self, *args, **kwargs):
    return '''<h1>SiteName</h1>
    <h2>Private Page</h2>
    <p><a href="logOut">Log Out</a></p>
    <p><a href="/">Go back home</a></p>'''
private = Login.check(private) = True

if name == "main": cherrypy.config.update({'sessionFilter.on': True}) cherrypy.root = Page() cherrypy.server.start() }}}

Reported by