What is code for devise authenticate_user! after g

2019-05-04 10:40发布

问题:

I realize that authenticate_user! is not explicitly defined in the gem files, but I am wondering for the typical app (authentication on model named User), what would the method look like. I need to know so that I can modify it slightly.

回答1:

I believe you linked to your own answer, the method it defines is

def authenticate_#{mapping}!(opts={})
  opts[:scope] = :#{mapping}
  warden.authenticate!(opts) if !devise_controller? || opts.delete(:force)
end

Which if we substituted the true class, in your case User, it would look like:

def authenticate_user!(opts={})
  opts[:scope] = :user
  warden.authenticate!(opts) if !devise_controller? || opts.delete(:force)
end

So it really calls out to warden and that is where the bulk of the authentication logic lies.

For a typical Rails application, The authenticate_user! method will be defined as an instance_method on ApplicationController.



回答2:

Devise uses Warden for authentication. And in order to use it Devise provides own authentication strategies implementing authenticate! method. This is what you need. You already have the first part of the code (from the link in your question), which is:

  def authenticate_user!(opts={})
    opts[:scope] = :user
    warden.authenticate!(opts) if !devise_controller? || opts.delete(:force)
  end

In the code above warden.authenticate! uses a method coming from Devise (implemented by Devise) depending on a chosen Devise strategy.

For example, the method that implements DatabaseAuthenticatable strategy is here: https://github.com/plataformatec/devise/blob/master/lib/devise/strategies/database_authenticatable.rb

the method that implements Rememberable strategy is here: https://github.com/plataformatec/devise/blob/master/lib/devise/strategies/rememberable.rb