CouchDB and Pylons: User Registration and Login
In the previous tutorial, we learned how to get CouchDB and Pylons up and running, as well as create a simple page counter. Now we are going to implement a simple user authentication system. This tutorial will teach you how to use formencode to validate forms and CouchDB to store our user data.
Let’s start by creating a new pylons project and some controllers.
$ paster create -t pylons userdemo $ cd userdemo $ paster controller main $ paster controller auth
Also, delete public/index.html.
For our controller main, we are going to add one action called index. This will be the main page for the site and will only be accessible for logged in users. If a user is not logged in, they will be redirected to the login page. Let’s add some routes for the main page, login, logout, and registration. Open up config/routing.py.
map.connect('/', controller='main', action='index') map.connect('/auth/login', controller='auth', action='login', conditions=dict(method=['GET'])) map.connect('/auth/login', controller='auth', action='login_post', conditions=dict(method=['POST'])) map.connect('/auth/logout', controller='auth', action='logout') map.connect('/auth/register', controller='auth', action='register', conditions=dict(method=['GET'])) map.connect('/auth/register', controller='auth', action='register_post', conditions=dict(method=['POST']))
For checking to see if a user is logged in, we will store a user_id in the session. Let’s make a decorator that we can add to our index action that will check to see if a user is logged in. If the user isn’t logged in, it will redirect to the login page. Your controllers/main.py should look have this:
from decorator import decorator def require_login(func, *args, **kwargs): """ Checks to see if user_id is in session """ if not 'user_id' in session: redirect_to('/auth/login') return func(*args, **kwargs) require_login = decorator(require_login) class MainController(BaseController): @require_login def index(self): return 'You are logged in! Click <a href="/auth/logout">here</a> to logout.'
Continue reading ‘CouchDB and Pylons: User Registration and Login’ »
