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.
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.
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.
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With