Hao's Thoughts

Ruby, Rails, Objective-C and everything else

Fancy Login With Red Light

I am not saying you are wrong if you are still redirecting the visitor to http://your_killer_app/login to input his/her credentials before letting him/her access the authentication required resource. I am just introducing another way of showing login page to you, the fancy way.

It’s fancy because it detects the links and forms requiring authencation in a fancy way. I am going to use Devise for authentication in the following example app, and you will learn how to have fancy login within your app.

Generate the app

1
$ rails new fancy_login_app

Generate the home controller

1
$ rails g controller home index

Generate the controller requiring authentications

1
$ rails g controller posts new create

Add Devise and red_light to the Gemfile

1
2
gem 'devise'
gem 'red_light'

Install the gems

1
2
3
$ bundle install
$ rails g devise:install
$ rails g red_light:install

Configure Devise views

1
$ rails g devise:views

The config/routes.rb should be something like

1
2
3
4
5
6
7
8
9
devise_scope :user do
  devise_for :users, :controllers => { :sessions => "sessions" }

  get "/login", :to => "sessions#new"
end

resources :posts, :only => [:new, :create]

root :to => "home#index"

Change app/controllers/posts_controller.rb to something like

1
2
3
4
5
6
7
8
9
class PostsController < ApplicationController
  before_filter authenticate_user!

  def new
  end

  def create
  end
end

Change app/views/home/index.html.erb to something like

1
<%= link_to "New Post", new_post_path %>

Fire the webrick

1
$ rails s

Visit localhost:3000, inspect the “New Post” link, you fill find the interesting rel

red_light add that rel to the link requiring authentication auto-magically. With the rel, you can play some javascript tricks to present a modal view when the link is clicked, here’s a demo.

You can also customize the config/initializers/red_light.rb to tell the red_light which before_filter should be auto blocked, for now, it’s only authenticate_user! there.

Comments