Skip to content
This repository

Rails authentication with email & password.

Fetching latest commit…

Octocat-spinner-32-eaf2f5

Cannot retrieve the latest commit at this time

Octocat-spinner-32 generators
Octocat-spinner-32 lib
Octocat-spinner-32 rails
Octocat-spinner-32 shoulda_macros
Octocat-spinner-32 test
Octocat-spinner-32 .gitignore
Octocat-spinner-32 CHANGELOG.textile
Octocat-spinner-32 KNOWN_ISSUES.textile
Octocat-spinner-32 LICENSE
Octocat-spinner-32 README.textile
Octocat-spinner-32 Rakefile
Octocat-spinner-32 clearance.gemspec
README.textile

Clearance

Rails authentication for developers who write tests.

We have clearance, Clarence.

Integration with Suspenders

Clearance is based on the same conventions and tools as Suspenders If you use it, you already have some configuration mentioned below.

Gem installation (Rails 2.1+)

In config/environment.rb:

config.gem “thoughtbot-clearance”, :lib => ‘clearance’, :source => ‘http://gems.github.com’, :version => ‘>= 0.4.9’

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.2.0’

Then:

rake gems:install rake gems:unpack rake gems:install RAILS_ENV=test rake gems:unpack RAILS_ENV=test

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.

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

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.

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 => ‘users’, :action => ‘new’

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”

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:

<div id="flash">
  <% flash.each do |key, value| -%>
    <div id="flash_<%= key -%>"><%= html_escape(value) %></div>
  <% end -%>
</div>

which is then rendered inside the body tag of your application layout:

<%= render :partial => ‘layouts/flashes’ -%>

Tests

The tests use Shoulda >= 2.9.1 and Factory Girl >= 1.1.5.

The generator will create a user factory in test/factories/clearance.rb unless
you have it defined somewhere else.

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

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 sign up (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).

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.

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 -%>

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

Usage: when bad things happen to good users

Clearance is HTTP fluent. If someone tries to hack the URLs for passwords or confirmations actions, they will be met with a 403 Forbidden HTTP status code. Internally, the Rails app will raise a ApplicationController::Forbidden error. This is a custom error in Clearance.

Layman’s 403 Forbidden definition:

“The request was a legal request, but the server is refusing to respond to it. Unlike a 401 Unauthorized response, authenticating will make no difference."

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 for the tip):

<% form_for :session, :url => session_path(:return_to => request.request_uri) do |form| %>

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)

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)
  1. store current time to display “last signed in at” message
    user.update_attribute(:last_signed_in_at, Time.now)
    sign_in(user)
    end
    end

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.

</code>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

Authors

Clearance was extracted out of Hoptoad. We merged the authentication code from two of thoughtbot’s client’s Rails apps. The following people have made significant contributions, suggestions, and generally improved the library. Thank you!

Dan Croak, Mike Burns, Jason Morrison, Joe Ferris, Eugene Bolshakov, Josh Nichols, Mike Breen, Marcel Görner, Bence Nagy, Ben Mabey, Eloy Duran, & Tim Pope.

Something went wrong with that request. Please try again.