auth.Sessions.Backend

  1. Backend() Class Introduction
  2. Backend*() General Usage
  3. Backend*() User and Session Objects
  4. Backend Methods
  5. Backend() Methods
  6. Example

Backend() Class Introduction

This class is a template (A.K.A. "virtual base class"?) for how the auth.Sessions Backends work. This class is never meant to be used directly by users, except for creation of a new Backend (for talking to a currently-unsupported database, for example).

The description of methods below is appropriate for getting a feel for how the backends work, and should be read in addition to any Backend-specific documentation (which in general will only cover how it differs from this).

Users who wish to build new Backends should see "tests/test009/testbe-fs" in the original JOTWeb source file for a comprehensive test which their backend should be able to pass.

Backend*() General Usage

The Backends store informaiton on the last session and user that were accessed. Methods like "userdel()" do not take any arguments, because they operate on the last retrieved user. So, to delete user "bob", you would do "backend.userget('bob'); backend.userdel()". Of course, you would want to check "backend.userget()" to ensure that it succeeded before deleting the user.

In the documentation on Methods, below, the setting and clearing of these values are documented in the Side-Effects section.

Backend*() User and Session Objects

Many backend routines return session and/or user objects. These objects are dictionaries, however only the elements marked as "Persistant" below should be modified. Changing items other than those marked as persistant will have undefined results.

The "payload" item is a dictionary, initially empty, which you may store your own program-specific data in. This dictionary is pickled and stored into the backend storage system, so it may contain arbitrary data. However, it's size may be limited by the backend. All backends must be able to store at least 1024 bytes of data, after pickling. Remember to call the "sessionsave()" and "usersave()" methods after updating the payload.

User objects have the following elements:

Session objects have the following elements:

Backend Methods

genSessionKey()

Arguments: None

Returns: (string) A random string of characters.

Side-effects: None.

Exceptions: None.

Description: Returns a straing of random characters, suitable for use as a session key. This is most likely to be used by users who are writing new Backend classes.

genAckKey()

Arguments: None

Returns: (string) A random string of characters.

Side-effects: None.

Exceptions: None.

Description: Returns a straing of random characters, suitable for use as an ack key. This is most likely to be used by users who are writing new Backend classes.

Backend() Methods

Example

These examples should work with any of the backends. In these examples, we are using the BackendFilesystem for demonstration.

Python Example: Adding a new user and session

   from jotweb.auth import Sessions
   sessionDir = '/tmp/sessiondir'
   be = Sessions.BackendFilesystem(sessionDir)

   #  add a user
   user = be.useradd('jafo', passwd = 'test1234')
   user['payload']['mydata'] = 'Test data stored in user'
   be.usersave()

   #  add a session
   session = be.sessionadd('jafo')
   session['payload']['mysessiondata'] = 'Test data stored with session.'
   be.sessionsave()

   #  validate user
   if be.userverify('jafo', 'test1234'):
      print 'User validated successfully'
   if not be.userverify('jafo', 'jafo'):
      print 'User didn't verify when we used the wrong password.'

   #  validate session
   newsession, newuser = be.sessionget(session['key'])
   if newsession:
      print 'Session validated successfully'

   #  delete session
   be.sessiondel()

   #  look up and then delete user
   be.userget('jafo')
   be.userdel()

HTML Form for Adding a new user:

Usually, you would never directly call the Backends directly from TAL, but below is an example of using input.SimpleForm.FormHandler() and the auth.Sessions.BackendFilesystem() code to create a form which allows adding users.

Create a file called "newuserform.html", which contains the form HTML:

   <form action="adduserform.html">
      Username: <input type="text" name="UserName" /><br />
      Password: <input type="password" name="Password" /><br />
      Password (Again): <input type="password" name="PasswordAgain" /><br />
      <input type="submit" value="Create User" />
   </form>

Create a file called "adduserform.html", which contains the HTML and code for adding a new user:

   <div tal:define="form adduserform/formvdt">
      <div tal:condition="not:form/geterrors">
         <!-- Form verification successful -->
         <div tal:define="result adduserform/adduser">
            <div tal:condition="not:result/failure">
               <!-- User created successfully -->
               <h1><font color="#ff0000">Added User</font></h1>
               User added successfully.
            </div>
            <div tal:condition="result/failure">
               <!-- User creation failed -->
               <h1><font color="#ff0000">Adding User Failed</font></h1>
               More detailed information: <span
                  tal:replace="result/reason">Failure Reason</span>
            </div>
         </div>
      </div>
      <div tal:condition="form/geterrors">
         <!-- Form had errors, display them -->
         <h1><font color="#ff0000">Form Errors</font></h1>
         <ul>
            <li tal:repeat="value form/geterrors" tal:content="value">Error</li>
         </ul>
      </div>
   </div>

Finally, make the Python code for handling the above, create "adduserform.py":

from jotweb.auth.Sessions import BackendFilesystem
   from jotweb.input import SimpleForm

   def formvdt():
      'Validate form data.'
      form = SimpleForm.FormHandler()
      if form.vdt_required('UserName'):
         form.cvt_makelowercase('UserName')    # conver to lower-case
         form.vdt_length('UserName', 8, 3)     # must have length of 3 to 8
         form.vdt_login('UserName')            # is a unix-like login name
      if form.vdt_required('Password'):
         form.vdt_length('Password', 50, 3)    # must have length of 3 to 50
         form.vdt_passwd('Password')
      form.vdt_equal('Password', 'PasswordAgain')

   def adduser():
      '''Add user.'''
      form = SimpleForm.FormHandler()
      be = BackendFilesystem('/tmp/sessiondata')
      try:
         be.adduser(form['UserName'], passwd = form['Password'])
      except Exception, e:
         return({ 'failure' : 1, reason : 'Received exception "%s"' % str(e) })
      return({ 'success' : 1 })

Index