Skip to content

How To: Find a user when you have their credentials

Josua Schmid edited this page Jun 4, 2018 · 6 revisions

From https://github.com/plataformatec/devise/issues/346, you can do the following:

user = User.find_for_authentication(:username => 'druidia')
user.valid_password?('12345')  # That's amazing! I have the same combination on my luggage!

Here's a convenient method for same:

class User
  def self.authenticate(username, password)
    user = User.find_for_authentication(:username => username)
    user&.valid_password?(password) ? user : nil
  end
end

Addendum: If you use confirmable, and don't want to authenticate the user if she isn't confirmed yet, you also need to call "active_for_authentication?"

Clone this wiki locally