开发者

How to set cookies when log in/out with Devise

I am using Devise for rails 3 application. For page caching, I nee开发者_JAVA技巧d 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.


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


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.


Adapted from @karl-rosaen answer this solution create a new initializer or add to the end of your devise.rb initializer.

This will add the cookie to remember the email if remember me options is set, if not it will delete the cookie

Warden::Manager.after_authentication do |user, auth, opts|
  if user.remember_me
    auth.cookies[:email] = {value: user.email, expires: 2.weeks.from_now}
  else
    auth.cookies.delete :email
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜