1.2.3.2 Password Protecting Code

The example below uses the auth database created in the example above and also uses a session file store. You can create a file store for the web.auth and web.session modules by creating a script-writable directory. In this case the directory is ../doc/src/lib/example-web-session.

Note: In specifying the directory for the session file store we have to use the path relative to the webserver.py script. With any other webserver this should be the path relative to the example itself ie just example-web-session. This also applies to the path to the database file examle-web-auth.db.

#!/usr/bin/env python

"""Auth Example. Username=john and Password=bananas (Case sensitive)"""

# show python where the web modules are
import sys, os
sys.path.append('../')
sys.path.append('../../../') 

import web, web.database, web.auth, web.session
import web.error; web.error.handle() # Automatically display errors

session = web.session.start(
    storage='file',
    dir='../doc/src/lib/example-web-session',
    app='app'
)
connection = web.database.connect(
    type='sqlite', 
    database='../doc/src/lib/example-web-auth.db'
)
cursor = connection.cursor()
user = web.auth.start(
    session, storage='database', cursor=cursor, 
    idle=100, expire=200
)

# No HTTP content-type headers should be printed before the user.valid() method
# if the autoLogin feature is enabled as this will print its own header. 

if user.valid():   # See if the User is signed in else present sign in form.
    print web.header() 
    if web.cgi.has_key('signOut'):
        user.signOut()
        print """<html><h1>Signed Out Now</h1><p><a href="%s">Sign in again</a>.
              </p></html>"""%os.environ['SCRIPT_NAME']
    else:
        
        print """
            <html>
            <h1>Welcome - You Signed In</h1>
            <p> Visiting this page again will result in you 
            seeing this page until you logout or the session expires.</p>
            <p> <b>Some Variables:</b><br>
            
            Username:       %s<br>
            Access Level:   %s<br>
            </p>
            <p>
            <a href="%s">Visit page again</a> |
            <a href="%s?signOut=True">Sign Out</a>
            </p>
            </html>"""%(
                user.username, 
                user.level['app'],
                os.environ['SCRIPT_NAME'],
                os.environ['SCRIPT_NAME']
            )

This example requires pysqlite. This comes with the binary distributions. If you are using the source distribution you can download it from http://pysqlite.sourceforge.net/.

You can test this example by starting the test webserver in scripts/webserver.py and visiting http://localhost:8080/doc/src/lib/webserver-web-auth.py on your local machine.

See About this document... for information on suggesting changes.