remember_me with warden

有些话、适合烂在心里 提交于 2019-12-04 07:03:20

Devise, which is an authentication solution on top of Warden, has a rememberable implementation.

Macario

Ok here's how I solved it

 # User model must have remember_token attribute

 # in config.ru
 use Rack::Cookies
 run MyApp

  # in lib/strategies.rb
  Strategies.add(:cookie) do
    def valid?
      env['rack.cookies']['user.remember.token']      
    end

    def authenticate!
      if user = User.find_by_remember_token(cookies['user.remember.token'])
        success! user
      else
        fail! "Could not log in"
      end
    end
  end

  Manager.after_authentication :scope => :user do |user, auth, opts|
    auth.env['rack.cookies']['user.remember.token'] = user.generate_remember_token! # sets its remember_token attribute to some large random value and returns the value
  end

  Manager.before_logout :scoper => :user do |user, auth, opts|
    user.update_attribute :remember_token, nil
  end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!