Question

I want to create a custom auth strategy for accessing the API. I followed the example code at Devise ignoring custom strategy.

The problem is that the valid? method in my Api strategy is never run (based on trying to pry in it).

My code:

module Devise
  module Strategies
    class Api < Devise::Strategies::Base
      def valid?
        binding.pry
        params[:request_source] == 'api'
      end

      def authenticate!
        #do stuff here

        if user
          success!(user)
        else
          warden.custom_failure!
          render :json=> {:success=>false, :message=>"Error with your login or password"}, :status=>401
        end
      end
    end

    Warden::Strategies.add(:api, Devise::Strategies::Api)

  end
end

and in the devise initializer:

config.warden do |manager|
  manager.default_strategies.unshift :api
end

What ever I do, it seems like Devise always use its default strategy. AFAIK, this should be enough...

-------EDIT--------

I require the strategy like this at the very top of my devise initializer:

require Rails.root.join('app/devise/strategies/api')

I know the strategy is loaded at boot time since if I put a pry call inside the class, it will start a pry session. But the Pry calls inside the methods are never run. :-S

Was it helpful?

Solution

Found the answer!

I had to use this:

config.warden do |manager|
  manager.default_strategies(scope: :user).unshift :api
end

to make it work. Weird thing is, a lot of the sample code I saw on the net did not use it :-S

OTHER TIPS

When are you requiring your custom strategy? Comparing to the example, you are adding the strategy there instead of in your initializer. You might try requiring the custom strategy at the top of your initializer to make sure it's loaded before you add it to default_strategies.

If that doesn't do the trick, don't be afraid to add some temporary puts statements right in devise itself where authenticate is called to check default_strategies. That is, if you're not already confortable using the debugger, which is what I would do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top