Reputation: 167
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 :)
Upvotes: 6
Views: 20844
Reputation: 4491
The password is not being saved as a bcrypt hash.
From the bycrypt documentation
https://github.com/codahale/bcrypt-ruby
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 http://api.rubyonrails.org/classes/ActiveModel/SecurePassword/ClassMethods.html
Upvotes: 10
Reputation: 106772
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
.
Upvotes: 10