Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set cookies when log in/out with Devise

I am using Devise for rails 3 application. For page caching, I need to set cookies for log in/out info.

What's the simplest way to set cookies when log in/out occurrs with Devise? I read 'how to customize controller' part but it seems to be a lot of work.

like image 263
Sam Kong Avatar asked Feb 01 '11 18:02

Sam Kong


People also ask

How Rails cookies work?

Cookies, Sessions and Flashes are three special objects that Rails gives you in which each behave a lot like hashes. They are used to persist data between requests, whether until just the next request, until the browser is closed, or until a specified expiration has been reached.

What is cookies in Ruby?

Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the cookie is available for retrieval.

What does Devise gem do?

Devise is the cornerstone gem for Ruby on Rails authentication. With Devise, creating a User that can log in and out of your application is so simple because Devise takes care of all the controllers necessary for user creation ( users_controller ) and for user sessions ( users_sessions_controller ).

What is session in Rails?

Rails provides a session object for each user that accesses the application. If the user already has an active session, Rails uses the existing session. Otherwise a new session is created. Read more about sessions and how to use them in Action Controller Overview Guide.


2 Answers

Since Devise is based on Warden, another solution is to use Warden's callbacks, e.g in your devise.rb:

  Warden::Manager.after_set_user do |user,auth,opts|
    auth.cookies[:signed_in] = 1
  end

  Warden::Manager.before_logout do |user,auth,opts|
    auth.cookies.delete :signed_in
  end
like image 195
Karl Rosaen Avatar answered Oct 12 '22 13:10

Karl Rosaen


It actually wouldn't be too hard to extend the devise SessionsController to add cookies on log in and log out, you could create a controller similar to this:

# app/controllers/sessions_controller.rb
class SessionsController < Devise::SessionsController
  # POST /resource/sign_in
  def create
    cookies[:sign_in] = "Sign in info you want to store"
    super
  end

  # GET /resource/sign_out
  def destroy
    cookies[:sign_out] = "Sign out info you want to store"
    super
  end
end

Then you would have to add the following to your routes.rb:

devise_for :users, :controllers => { :sessions => "sessions" }

That should get you most of the way there.

like image 38
Braden Becker Avatar answered Oct 12 '22 11:10

Braden Becker