1.2.9 Examples

##
1.2.9 Examples

Putting together everything in the previous sections gives us this full application:

    #!/usr/bin/env python

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

    # show python where the modules are
    import sys; sys.path.append('../'); sys.path.append('../../../')
    import web.error; web.error.enable()
    import web, web.database

    # Setup a database connection
    connection = web.database.connect(
        adapter="snakesql",
        database="webserver-auth",
        autoCreate = 1,
    )
    cursor = connection.cursor()

    # Obtain a session store
    import web.session
    driver = web.session.driver('database', environment='testEnv', cursor=cursor)

    if not driver.completeSessionEnvironment():
        driver.removeSessionEnvironment(ignoreErrors=True)
        driver.createSessionEnvironment()

    manager = web.session.manager(driver=driver)
    if not manager.load():
        manager.create()

    # Obtain Auth objects
    import web.auth
    authSession = web.auth.session(manager.store('auth'), expire=0, idle=10)
    driver = web.auth.driver('database', environment='testEnv', cursor=cursor)
    authManager = web.auth.manager(driver=driver)
    if not driver.completeAuthEnvironment():
        driver.removeAuthEnvironment(ignoreErrors=True)
        driver.createAuthEnvironment()
        authManager.addApplication('app')
        authManager.addUser(
            'john',
            'bananas',
            'John',
            'Smith',
            'johnsmith@example.com',
        )
        authManager.addUser(
            'norights',
            '123',
        )
        authManager.setAccessLevel('john', 'app', 1)

    # Get the username of the current logged in user from the session
    print web.header()
    username = authSession.username()
    valid = False
    if username and authManager.userExists(username):
        user = authManager.getUser(username)
        if user.level.has_key('app') and user.level['app'] > 0:
            print 'Username %s is signed in'%user.username
            valid = True
    if not valid:
        authSession.signOut()
        # Try to login
        import web.auth.handler.signIn
        signInHandler = web.auth.handler.signIn.SignInHandler(
            session = authSession,
            manager = authManager,
        )
        form = signInHandler.handle()
        if form:
            # Display the error form
            print '<html><body><h1>Please Sign In</h1>%s</body></html>'%form
        else:
            # We have just signed in
            username = authSession.username()
            valid = False
            if username and authManager.userExists(username):
                user = authManager.getUser(username)
                if user.level.has_key('app') and user.level['app'] > 0:
                    print 'Signed in successfully'
                    valid = True
            if not valid:
                print "You do not have suitable access rights to use this application"

    connection.commit()
    connection.close()

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. The username is `john` and the password is `bananas`.

A simpler version using the `web.auth.start()` function is here:

    #!/usr/bin/env python

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

    # show python where the modules are
    import sys; sys.path.append('../'); sys.path.append('../../../')
    import web.error; web.error.enable()
    import web, web.database

    # Setup a database connection
    connection = web.database.connect(
        adapter="snakesql",
        database="webserver-auth-simple",
        autoCreate = 1,
    )
    cursor = connection.cursor()

    import web.auth

    # If the auth environment is created, setup some information
    def setup(userManager):
        userManager.addApplication('app')
        userManager.addUser(
            'john',
            'bananas',
            'John',
            'Smith',
            'johnsmith@example.com',
        )
        userManager.setAccessLevel('john', 'app', 1)

    # Create the auth objects
    error, username = web.auth.start(
        environmentName='testEnv',
        environmentType='database',
        cursor = cursor,
        expire=10,
        setupSessionEnvironment=1,
        setupAuthEnvironment=1,
        setup = setup, # using the setup function above
        stickyData = {'testVar':'True'},
        action = 'webserver-web-auth-simple.py',
        redirect = '/'
    )
    # print some output
    if error:
        print error # Error contains a form to display to allow users to sign in
    else:
        print 'User %s is signed in.' % username

    connection.commit()
    connection.close()

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-simple.py on your local machine. The username is `john` and the password is `bananas`.