How do I add a strategy to Devise

2019-05-01 14:43发布

问题:

I'm trying to add a really simple strategy to devise, and it doesn't seem to be working. Here is the code that I am trying to use

#config/initializers/devise.rb
Devise.setup do |config|
  config.orm = :mongo_mapper

  config.warden do |manager|
    manager.strategies.add(:auto_login_strategy) do 
      def valid?
        params[:auto_login]
      end

      def authenticate!
        u = User.find(:first)
        u.nil? ? fail!("No created users") : success!(u)
      end
    end
    manager.default_strategies(:scope=>:user).unshift :auto_login_strategy
  end  
end

The code is supposed to check the params for an 'auto_login' parameter, and if present, find the first user it can and log them in. I have skipped security measures entirely to just get a basic test case working. When I try to log into a controller that has a before_filter authenticate_user! (i.e. localhost:3000/test?auto_login=true), it can't log me in and redirects me to the login page. What am I doing wrong?

回答1:

You may want to try adding it directly to Warden::Strategies:

class MyStrategy
  def valid?...
  def authenticate!...
end

Warden::Strategies.add(:database_authenticatable, MyStrategy)

I did this a while ago, but then ended up not needing it. Let me know if I've remembered it correctly.