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 :)

2 Answers

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.

0

The password is not being saved as a bcrypt hash.

From the bycrypt documentation

require 'bcrypt' my_password = BCrypt::Password.create("my password")#=> "$2a$10$vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa" my_password.version #=> "2a" my_password.cost #=> 10 my_password == "my password" #=> true my_password == "not my password" #=> false my_password = BCrypt::Password.new("$2a$10$vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa") my_password == "my password" #=> true my_password == "not my password" #=> false 

So your code to store your user's password hash would look this

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 = BCrypt::Password.create(data[:info][:password]) end end 

Then you can test it like the documentation says

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like