foundev.github.io

Python Web Framework Series – Pylons: Part 6 Basic Authorization With AuthKit

Last post we left off with very basic database access, and testing story completed. Now we’re going to look at basic Authorization and Authentication with AuthKit. NOTE: most of this post is just an aggregation of a couple of chapters in the Pylons Book since this setup is a good base starting point. Read the previous link to the Pylons Book for more in depth coverage of this topic. 

Setting Up AuthKit

First lets make sure we have AuthKit installed: easy_install AuthKit. For this post we’re working with AuthKit 0.4.3, your mileage may vary if you read this post in the future and are using a different version. Now that we have Authkit installed open up pylonsforumconfigmiddleware.py add the following imports:

 

 

import authkit.authenticate
from authkit.permissions import ValidAuthKitUser

 

and then add somewhere inside the if asbool(full_stack): code block.

permission = ValidAuthKitUser()
app = authkit.authorize.middleware(app, permission)
app = authkit.authenticate.middleware(app,app_conf)

 

 

in development.ini add this to the end of your [app:main] section

authkit.setup.enable = true
authkit.setup.method = form, cookie
authkit.form.authenticate.user.type = authkit.users.sqlalchemy_driver:UsersFromDatabase
authkit.form.authenticate.user.data = pylonsforum.model
authkit.cookie.secret = secret string
authkit.cookie.signoutpath = /home/signout

Open your home.py controller and for now add a “signout” action:

def signout(self):
    return “You’ve been signed out”

Now in your websetup.py we have a ton to add to get the basic setup working. Start right after imports and add these line.

from authkit.users.sqlalchemy_driver import UsersFromDatabase

next add the following in your “setup_app” method after load_environment

    from pylonsforum.model import meta
    meta.metadata.bind = meta.engine
    filename = os.path.split(conf.filename)[1]
    log.info(“Adding the AuthKit model…”)
    users = UsersFromDatabase(model)
    meta.metadata.create_all(checkfirst=True)
    log.info(“Adding roles and uses…”)
    users.user_create(“admin”, password=“admin”)

For the final piece delete your development.db file and run paster setup-app development.ini to recreate it with the AuthKit user model. Now you have very basic authentication working in your site

http://localhost:5000 reveals:

Picture 2

type in “admin” for the username and password and it should let you pass.  Note going back to the site will not bring up a password box again.

http://localhost:5000/home/signout

will remove your cookie and you’ll see the sign in form once more if you go to http://localhost:5000 .  Stayed tuned for more posts as I go more in depth with the different features and customizations of AuthKit.