Monday, March 21, 2011

Google OpenID via Rails

So you've decided to write a web application. You are probably going to want to allow users to log in. Maybe its because you don't want to mess up password security, or maybe its because you feel the web doesn't need yet one more username/password combination, but you've decided to use OpenID. Here's how I've done it in rails.

For this, I am very much leveraging http://blog.sethladd.com/2010/09/ruby-rails-openid-and-google.html. Rather than repeat everything that Seth Ladd said, I will just include the differences from him.

First, I am starting completely from scratch, so the first step is to create a rails project.

rails new login

Then I need a user model:

rails generate model User identifier_url:string email:string
                          first_name:string last_name:string
rake db:migrate

The above two steps replace step 0 from Seth Ladd's blog post.

For step 1, here is what my Gemfile looks like:
  1 source 'http://rubygems.org' 
  2  
  3 gem 'rails', '3.0.4'
  4 gem 'sqlite3' 
  5 gem 'haml' 
  6 gem 'haml-rails' 
  7 gem 'ruby-openid' 
  8 gem 'rack-openid' 
  9 gem 'mongrel', '>= 1.2.0.pre2'
 10  
 11 group :development do
 12   gem 'rspec-rails' 
 13 end 
 14  
 15 group :test do
 16   gem 'rspec' 
 17   gem 'webrat' 
 18 end
There are only a couple things of note in this Gemfile. As I've mentioned before, I like haml, hence lines 5-6. Lines 7-8 are the lines from Seth's post. Line 10 is because WEBrick causes errors when I try to use the OpenID authentication and the current version of mongrel isn't working for me (Windows platform). Oh, and lines 11-18 are lines I pulled from Ruby On Rails 3 Tutorial by Michael Hartl. Even though I am not doing any testing here, it seems like a good idea to enable it.

Then, of course, I ran:

bundle install

Steps 2-6 I exactly followed Seth's post. For step 7, I basically followed his post, but used Haml rather than Erb. For step 8, I created an action controller:

rails generate controller Actions view

My action controller looks like:
  1 class ActionsController < ApplicationController
  2   before_filter :ensure_signed_in  
  3  
  4   def view 
  5   end
  6 end
and my app/views/actions/view.html.haml looks like:
  1 %p  
  2   = current_user.first_name  
  3   = current_user.last_name  
  4   (  
  5   = current_user.email  
  6   )  
  7 %p= current_user.identifier_url
And with that I have a simple app that uses OpenID for authentication. I test it by running:

rails s

and then going to http://127.0.0.1:3000/actions/view in my browser. As expected, I get redirected to google, and then after logging in, I get sent back, and I can see my information. Doing something useful with this will be left as an exercise for the reader.

No comments: