-
-
Notifications
You must be signed in to change notification settings - Fork 467
Usage
The following applies to Clearance >= 0.11.0.
sign_in_as
, sign_out
, should_deny_access
and more helpers are available in your test suite. Look in controller_helpers.rb and deny_access_matcher.rb 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_respond_with :success
end
If you want to authorize users for a controller action, use the require_login
method in a before_action
.
class WidgetsController < ApplicationController
before_action :require_login
def index
@widgets = Widget.all
end
end
Upon successful login, clearance will redirect the user to the page they were denied access, to the default redirect URL configured in the clearance initializer, or the URL specified in an overridden sessions#url_after_create
method.
If you want to have a sign in form on every page and redirect the user to the same page after sign in, you can add a before_filter
that sets the session[:return_to]
value.
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:
class SessionsController < Clearance::SessionsController
protected
def url_after_create
new_blog_post_path
end
end
You'll also need to add an appropriate declaration in your config/routes.rb file to tell your app to use your overriding controller instead of the controller inside Clearance's engine. Following the example above, to override Clearance's sessions controller, you'd add this to your config/routes.rb file (before the Clearance::Routes.draw(map) call):
resource :session,
:controller => 'sessions',
:only => [:new, :create, :destroy]
You also need to add code such as the following to your routes.rb:
match '/sign_out' => 'sessions#destroy', :via => :delete
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 reset)
- PasswordsController#url_after_forbidden (user clicks link in password reset email after resetting)
- PasswordsController#url_after_update (password)
- ConfirmationsController#url_after_create (confirmation)
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_in that you can overwrite with that logic. Be sure to write tests!
class ApplicationController < ActionController::Base
include Clearance::Authentication
# sign_in needs to be public for the `sign_in_as` controller spec helper to work
hide_action :sign_in
def sign_in(user)
# store current time to display "last signed in at" message
user.update_attribute(:last_signed_in_at, Time.now) if user
super user
end
end