ruby-on-railsrubyruby-on-rails-4encryptionbcrypt-ruby

How to encrypt password with has_secure_password in Rails 4.2


I've an API and I installed the next gem

 gem 'bcrypt' 

And into my user model I specific that:

has_secure_password

My DataBase Have a field with name

password_digest

And when run the seeders Yea the password is encrypted, But when try to create a new user from my method the password is normal, This my method for create new user

def self.from_auth(data)
    User.where(email: data[:email]).first_or_create do |user|
        user.email = data[:info][:email]
        user.name = data[:info][:name]
        user.provider = data[:info][:provider]
        user.uid = data[:info][:uid]
        user.password_digest = data[:info][:password]
    end
end

Thanks :)


Solution

  • Do not write the password_digest attribute directly. Use password (and probably password_confirmation) instead and Rails will do the magic for you.

    Change

    user.password_digest = data[:info][:password]
    

    to

    user.password              = data[:info][:password]
    user.password_confirmation = data[:info][:password]
    

    I advise to read the docs for has_secure_password.