Authentication Setup with Merb Auth and Merb Stack
This week I was lucky enough to spend two days at the Merb Sprint. At the sprint I spent some time testing the install and setup process for the Merb Stack and merb_auth (the merb authentication gem). Dan Neighman (aka hassox) spent some time with me going over the merb_auth process and this is my attempt to pass the information on.
This walkthrough will take you through the steps to get a Merb app up and running with a protected resource. It assumes you are running Merb 0.9.9 or greater with the Merb Stack (merb-core, merb-more, and datamapper).
Lets start at the beginning and create an app
$ merb-gen app authentication_app
$ cd authentication_app
By default merb-gen app will create a user model for you in app/models/user.rb. The model is there, but we still need to create the table in the database and add a user to authenticate with. Lets do that now.
$ rake db:auto_migrate
To create our first user we can drop into Merb's irb console mode with merb -i. Like Rails' script/console, merb -i gives you access to your models and other classes.
$ merb -i
u = User.new
u.login = 'joe'
u.password = u.password_confirmation = 'password'
In order to test authentication we need something to protect. Any controller would work, but lets create a resource.
$ merb-gen resource secret
We will need to add a route to the resource also
To protect a controller with authentication we can use the before filter ensure_authenticated
class Secrets < Application
Everything should now be setup in our app. Lets give it a run through.
First you need to start you merb server. Make sure you are in your merb app's root directory.
Now you can test access to your resource is denied before authentication:
Login in and try to access the resource again:
You should now be able to access the resource. Awesome.