1.14.3.6 web.wsgi.auth - User Permission Handling

Auth handling middleware. If an application returns a '403 Forbidden' status message, the middleware intercepts it and instead provides a sign in form and sign in functionality.

Once a user is signed in, the user's information is added to the environ dictionary as environ['web.auth.user'] for authorisation.

class Session( application, driver, [store=None], [expire=0], [idle=0], [autoCreate=0], [app='auth'], [template='<html><body><h1>Please Sign In</h1>%(form)s<p>%(message)s</p></body></html>'],[redirectMethod='http'], [**driverParams])

application
A WSGI application or middleware component

driver
The type of driver being used. Currently only 'database' is allowed

**driverParams
Any parameters to be specified in the format name=value which are needed by the driver specified by driver

autoCreate
If set to True the necessary tables will be created (removing any existing tables) if any of the tables are missing and a user named john with a password bananas will be set up with an access level of 1 to the application app. This is designed for easy testing of the module.

encryption
The encryption method used to encrypt the password. Can be None or 'md5'. Warning you cannot change the encryption method once a user is added without resetting the password.

store or app
Store should be a valid web.session Store object for storing the auth session information. If not specified, a store can be obtained from the environ['web.session'] object if the name of the store to used is specified by app.

expire
An integer specifying the number of seconds before the user is signed out. A value of 0 disables the expire functionality and the user will be signed in until they sign out. Note: If the underlying session expires, the cookie is removed or the sign in idles before the expire time specified in expire the user will be signed out.

idle
An integer specifying the maximum number of seconds between requests before the user is automatically signed out. A value of 0 disables the idle functionality allowing an unlimited amount of time between user requests. Note: If the underlying session expires, the cookie is removed or the sign in expires before the idle time specified in idle the user will be signed out.

template
A string containing %(form)s and %(message)s for dictionary replacement of the sign in form and error message respectively.

redirectMethod
Determines how the application should redirect back to the original code once a user is signed in. The default is HTTP redirection specified with redirectMethod='http' but alternatively a META refresh can be used, redirectMethod='metaRefresh' Warning: There currently appears to be a bug in the WSGI Server preventing HTTP redirection from working so META refresh redirection should be used.

Entries added to environ:

environ['web.auth']
An AuthManager object as returned by web.auth.manager()

environ['web.auth.user']
A user object for the current signed in user

environ['REMOTE_USER']
The username of the signed in user

The example below demonstrates how to check if a user is signed in and if they are not signed in, provide them with a sign in form and handle the submissions until they are signed in.

import sys; sys.path.append('../')
from web.wsgi import *

def simpleApp(environ, start_response):
    if not environ.has_key('web.auth.user'): # No user signed in
        start_response('403 User not signed in', [])
        return []
    elif not environ['web.auth.user'].authorise(app='app', level=1):
        start_response('403 The user does not have permission to access this application', [])
        return []
    else:
        start_response('200 OK', [('Content-type','text/html')])
        if environ['web.cgi'].has_key('mode') and environ['web.cgi']['mode'].value == 'signOut':
            environ['web.auth'].signOut()
            return ["""<html>
                <head><title>Auth Example</title></head>
                <body bgcolor="#ffffcc"><h1>Signed Out</h1><p><a href="auth">Sign in</a></p></body>
                </html>"""]
        else:
            return ["""<html>
                <head><title>Auth Example</title></head>
                <body bgcolor="#ffffcc"><h1>Congratulations!</h1>
                <p>Signed in!</p>
                <p><a href="auth?mode=signOut">Sign out</a>, <a href="auth">Visit again</a></p>
                </body></html>"""]

# Middleware Setup
application = error.Error(
    database.Database(
        session.Session(
            cgi.CGI(
                auth.Auth(
                    simpleApp, 
                    driver='database',
                    autoCreate=1,
                    expire=0,
                    idle=10,
                    template = """
                        <html>
                        <head><title>Auth Example</title></head>
                        <body bgcolor="#ffffcc">
                        <h1>Sign In</h1>
                        %(form)s
                        <p>%(message)s</p>
                        </body>
                        </html>
                    """,
                    redirectMethod='metaRefresh'
                ),
            ),
            expire = 1000,
            autoCreate = 1,
            driver='database',
        ),
        adapter = 'snakesql',
        database = 'wsgi-auth',
        autoCreate = 1
    ),
)

The message displayed under the sign in box is whatever you specify as the message after 403 in the status of start_response().

You can test this example by running the WSGI server scripts/WSGIServer.py and visiting http://localhost:8000/auth