ruby on rails - Updating password with BCrypt -


when login username , password bcrypt checks no problem, fine.

but when go through process of recovering password , try login new password bcrypt never returns true.

the code have follows:

before_save :encrypt_password before_update :encrypt_password  def authenticate    player = player.find_by(mail: self.mail)    unless player.nil?    current_password = bcrypt::password.new(player.password)    if current_password == self.password     player    else      nil    end  end end  private def encrypt_password     unless self.password.nil?     self.password = bcrypt::password.create(self.password) end 

i'm using rails 4

you don't need before_update callback.

when creating new record (user in case), before_save triggered. right behavior.

but when updating record, both before_update , before_save triggered, means password column encrypted twice. that's why unexpected behavior.

check this page more information callbacks.


what's more, think it's bad idea make password real column in database. need column called encrypted_password in database , making password virtual attribute.

so can write encrypt_password method this:

def encrypt_password     unless self.password.nil?     self.encrypt_password = bcrypt::password.create(self.password) end 

which gave no chance make mistake made.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -