Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is code for devise authenticate_user! after generated for :user

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.

like image 462
Abram Avatar asked Aug 26 '15 21:08

Abram


People also ask

What does devise Authenticate_user do?

Devise also comes with some very useful helper functions: before_action :authenticate_user! — Add to any controller to limit access to an action unless a user is logged in.

What is the use of devise gem?

Devise is an excellent authentication system made for Rails that allows us to easily drop-in User functionality into our project. Devise only includes an email and password for registration, let's also add our own username to our User model. We also want to have a unique index on our username.


2 Answers

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.

like image 108
yez Avatar answered Oct 11 '22 08:10

yez


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

like image 3
chumakoff Avatar answered Oct 11 '22 06:10

chumakoff