84

Where is devise implementation of authenticate_user! method?

I have been looking for it and have not found it so far.

Arslan Ali
  • 17,418
  • 8
  • 58
  • 76
Greg
  • 34,042
  • 79
  • 253
  • 454

3 Answers3

88

It's in lib/devise/controllers/helpers.rb1 and is generated dynamically (user being only one of the possible suffixes):

def self.define_helpers(mapping) #:nodoc:
    mapping = mapping.name

    class_eval <<-METHODS, __FILE__, __LINE__ + 1
      def authenticate_#{mapping}!(opts={})
        opts[:scope] = :#{mapping}
        warden.authenticate!(opts) if !devise_controller? || opts.delete(:force)
      end

      def #{mapping}_signed_in?
        !!current_#{mapping}
      end

      def current_#{mapping}
        @current_#{mapping} ||= warden.authenticate(:scope => :#{mapping})
      end

      def #{mapping}_session
        current_#{mapping} && warden.session(:#{mapping})
      end
    METHODS

    ActiveSupport.on_load(:action_controller) do
      helper_method "current_#{mapping}", "#{mapping}_signed_in?", "#{mapping}_session"
    end
  end
jupp0r
  • 4,502
  • 1
  • 27
  • 34
  • Please see http://stackoverflow.com/questions/32237346/what-is-code-for-devise-authenticate-user-after-generated-for-user – Abram Aug 26 '15 at 21:56
  • 2
    so how do I access it explicity. this call doesn't work>> `Devise::Controllers::Helpers.authenticate_user!` – Vipin Verma Mar 02 '16 at 09:53
25

When you add devise to rails, you'll typically add in config/routes.rb:

devise_for :user

This is defined in the Devise Mapper class.

which calls Devise.add_mapping for every resource passes to devise_for

the Devise module's add_mapping method is defined here, which subsequently calls define_helpers, which defines authenticate as discussed in other answers.

Smar
  • 8,109
  • 3
  • 36
  • 48
Ultrasaurus
  • 3,031
  • 2
  • 33
  • 52
7

It's declared using some metaprogramming here - https://github.com/plataformatec/devise/blob/master/lib/devise/controllers/helpers.rb#L46-49

class_eval <<-METHODS, __FILE__, __LINE__ + 1
  def authenticate_#{mapping}!(opts={})
    opts[:scope] = :#{mapping}
    warden.authenticate!(opts) if !devise_controller? || opts.delete(:force)
  end
  ...
end
Dogbert
  • 212,659
  • 41
  • 396
  • 397