So say you are using devise and have none of the has_secure_password medthod available to you. One should learn the bcrypt gem... and needs to abstract some methods in order to parse an encrypted password. Cool, Bcrypt can do that, as located here. Here is my modified code in order to confirm if a new password in order to apply a boolean value to an inputed password.
defauthenticate(unencrypted_password)ifBCrypt::Password.new(encrypted_password)==unencrypted_password&&selfbcrypt=::BCrypt::Password.new(encrypted_password)# creates a bcrypt variable if the encrypted passwors result is true# => "$2a$10$wgOzLhy84peHUD9wr9UkgOKRpwfls/0h48NYVvKIOdUdbz3XOEpSK" password=::BCrypt::Engine.hash_secret(password,bcrypt.salt)# then salts the new password# => "$2a$10$VUNoD3xdAp7ytTIsTyH5feY.DNUKA4efIdkcI6ViBQ532o8lyNV/e" user=nilunlessreset_secure_compare(password,encrypted_password)returntrueelseBCrypt::Password.new(encrypted_password)!=unencrypted_password&&selfreturnfalseendend
You might be wondering what the reset_secure_password method is doing. Well, it is pulled from the Devise docs and is preventing timing attacks, when an attacker attempts to compromise an encryption by analyzing the time taken in order to execute the password and salting algorithms.
Cool, now I can pass my current_password attribute to make sure it is true. I need to make a custom Active Record Validations.
If this validates, encrypted_password on the database returns true. Now I need validations for events with blank fields (I want nothing to happen), and also, if current_password is blank and new_password and present, visa versa.
validate:incorrect_password_update_validator,on::updatevalidate:correct_password_update_validator,on::updatevalidate:current_password_present,on::updatevalidate:new_password_present,on::updatevalidate:current_password_true_present,on::updateprivatedefcurrent_password_true_presentifself.authenticate(current_password)==trueandnew_password.blank?andcurrent_password.present?errors.add(:new_password," needs to be filled out.")endenddefcurrent_password_presentifself.authenticate(current_password)==falseandnew_password.present?andcurrent_password.blank?errors.add(:current_password," needs to be filled out.")endenddefnew_password_presentifself.authenticate(current_password)==falseandnew_password.blank?andcurrent_password.present?errors.add(:new_password," needs to be filled out.")endenddefincorrect_password_update_validatorifself.authenticate(current_password)==falseandcurrent_password.present?andnew_password.present?errors.add(:current_password," does not match.")endenddefreset_secure_compare(a,b)returnfalseifa.blank?||b.blank?||a.bytesize!=b.bytesizel=a.unpack"C#{a.bytesize}"res=0b.each_byte{|byte|res|=byte^l.shift}res==0end
Now, all use cases of the user improperly editing the form result in false and a validation error occurs.