h1. Clearance
Rails authentication for developers who write tests.
"We have clearance, Clarence.":http://www.youtube.com/v/mNRXJEE3Nz8
h2. Integration with Suspenders
Clearance is based on the same conventions and tools as "Suspenders":http://github.com/thoughtbot/suspenders If you use it, you already have some configuration mentioned below.
h2. Gem installation (Rails 2.1+)
In config/environment.rb:
config.gem "thoughtbot-clearance",
:lib => 'clearance',
:source => 'http://gems.github.com',
:version => '>= 0.4.8'
In config/environments/test.rb:
config.gem 'thoughtbot-shoulda',
:lib => 'shoulda',
:source => "http://gems.github.com",
:version => '>= 2.9.1'
config.gem 'thoughtbot-factory_girl',
:lib => 'factory_girl',
:source => "http://gems.github.com",
:version => '>= 1.1.5'
Then:
rake gems:install
rake gems:unpack
rake gems:install RAILS_ENV=test
rake gems:unpack RAILS_ENV=test
h2. The generator
Make sure the development database exists and run the generator:
script/generate clearance
A number of files will be created and instructions will be printed.
You may already have some of these files. Don't worry. You'll be asked if you want to overwrite them.
h2. Modules
Clearance works by mixing behavior into tests, controllers, and models. For any file that you do not want to overwrite, include the corresponding Clearance module. They are namespaced exactly like the directory structure of a Rails app.
Application controller example:
class ApplicationController < ActionController::Base
include Clearance::App::Controllers::ApplicationController
end
User model example:
class User < ActiveRecord::Base
include Clearance::App::Models::User
end
User test example:
class UserTest < Test::Unit::TestCase
include Clearance::Test::Unit::UserTest
end
h2. The migration
The generator will also create a migration to add a "users" table and run it. If the table already exists in the database, the migration will just add fields and indexes that are missing and required by Clearance. If the migration fails, the generator will revert all changes back.
h2. Routes
Clearance will add these routes to your routes.rb:
map.resources :users, :has_one => [:password, :confirmation]
map.resource :session
map.resources :passwords
Please note that Clearance depends on root_url, so please make sure that it is defined to *something* in your config/routes.rb:
map.root :controller => 'home'
h2. Environments
You need to define HOST constant in your environments files. In config/environments/test.rb and config/environments/development.rb it can be:
HOST = "localhost"
While in config/environments/production.rb it must be the actual host your application is deployed to because the constant is used by mailers to generate URLs in emails.
In config/environment.rb:
DO_NOT_REPLY = "donotreply@example.com"
h2. The flash
You will need to display the success, failure, and notice flash messages in your layout. We recommend creating an app/layouts/_flashes.html.erb partial similar to the _flashes partial in Suspenders:
<% flash.each do |key, value| -%>
<%= html_escape(value) %>
<% end -%>
which is then rendered inside the body tag of your application layout:
<%= render :partial => 'layouts/flashes' -%>
h2. Tests
The tests use "Shoulda":http://thoughtbot.com/projects/shoulda >= 2.9.1 and "Factory Girl":http://thoughtbot.com/projects/factory_girl >= 1.1.5.
The generator will create a user factory in test/factories/clearance.rb unless
you have it defined somewhere else.
h2. Features
If you are using Cucumber on your application Clearance comes with a feature generator:
script/generate clearance_features
All of the files generated should be new with the exception of the features/support/paths.rb file. If you have not modified your paths.rb then you will be okay to replace it with this one. If you need to keep your paths.rb file then you will need to add these locations in your paths.rb manually:
def path_to(page_name)
case page_name
...
when /the sign up page/i
new_user_path
when /the sign in page/i
new_session_path
when /the password reset request page/i
new_password_path
...
end
h2. Usage: basic workflow
Rails authentication with Clearance uses the standard approach thoughtbot and our clients have agreed upon.
Users sign up (UsersController) using an email address and a password (User model). They get an email (ClearanceMailer) with a confirmation link to confirm their registration (ConfirmationController).
Signed up and email confirmed users can sign in and out (SessionsController). If they forget their password, they request an email (ClearanceMailer) containing a link to change it (PasswordsController).
h2. Usage: actions which require an authenticated user
To protect your controllers with authentication add:
class ProtectedController < ApplicationController
before_filter :authenticate
The filter will ensure that only authenticated users can access the controller. If someone who's not signed in tries to access a protected action:
* the URL is stored in the session,
* the user is redirected to sign in page, and
* after successful authentication will be be redirected back to that URL.
h2. Usage: signed_in?, current_user
Clearance provides two methods that can be used in controllers, helpers, and views to check if current user is authenticated and get the actual user:
* signed_in?
* current_user
<% if signed_in? -%>
Hello, <%= current_user.name %>!
<% else -%>
Please <%= link_to 'Sign in', new_session_path %>
<% end -%>
h2. Usage: mass assignment
Please note that all User attributes except email, password and password_confirmation are protected from mass assignment by default. Use attr_accessible to enable it for your custom attributes.
class User < ActiveRecord::Base
include Clearance::App::Models::User
attr_accessible :first_name, :last_name
end
h2. Hooks: return_to parameter
To specify where to redirect a user (say you want to have a sign in form on every page and redirect the user to the same page) after he/she signs in, you can add a "return_to" parameter to the request (thanks to "Phillippe":http://www.sivarg.com/2009/01/clearance-coming-from-where-your-were.html for the tip):
<% form_for :session, :url => session_path(:return_to => request.request_uri) do |form| %>
h2. Hooks: url_after_create, url_after_update, url_after_destroy
Actions that redirect (create, update, and destroy) in Clearance controllers are customizable. If you want to redirect a user to a specific route after signing in, overwrite the "url_after_create" method in the SessionsController:
class SessionsController < ApplicationController
include Clearance::App::Controllers::SessionsController
private
def url_after_create
new_blog_post_path
end
end
There are similar methods in other controllers as well:
UsersController#url_after_create (sign up)
SessionsController#url_after_create (sign in)
SessionsController#url_after_destroy (sign out)
PasswordsController#url_after_create (password request)
PasswordsController#url_after_update (password)
ConfirmationsController#url_after_create (confirmation)
h2. Hooks: sign_user_in
Say you want to add a last_signed_in_at attribute to your User model. You would want to update it when the User signs in.
Clearance has a method named sign_user_in that you can overwrite with that logic. Be sure to call sign_in(user) at the end (and write tests!).
class ApplicationController < ActionController::Base
include Clearance::App::Controllers::ApplicationController
private
def sign_user_in(user)
# store current time to display "last signed in at" message
user.update_attribute(:last_signed_in_at, Time.now)
sign_in(user)
end
end
h2. Write your own tests with Clearance's helpers
sign_in_as, sign_out, should_be_signed_in_as, should_not_be_signed_in, should_deny_access, signed_in_user_context, and more helpers are available in your test suite. Look in vendor/gems/clearance/shoulda_macros for the full list.
context "when signed in on GET to new" do
setup do
@user = Factory(:email_confirmed_user)
sign_in_as @user
get :new
end
should_be_signed_in_as { @user }
end
h2. Authors
* thoughtbot, inc.
* Dan Croak
* Mike Burns
* Jason Morrison
* Eugene Bolshakov
* Josh Nichols
* Mike Breen