Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails > Devise password encryption

I'm trying to implement a method to allow password to be changed from another service outside devise anyhow.

# Profile password change
def change_password(oldpass, newpass)
    pepper  = nil
    cost    = 10

    # Encrypt plain text passwords
    encrypt_old     = ::BCrypt::Password.create("#{oldpass}#{pepper}", :cost => cost).to_s

    # Validate old
    if self.encrypted_password == encrypt_old
        encrypt_new     = ::BCrypt::Password.create("#{newpass}#{pepper}", :cost => cost).to_s
        self.encrypted_password = encrypt_new
        self.save
    else
        Logger.new("Wrong old password!")
    end
end

It seems i got the password encryption wrong oldpass contains a plain text of old password i need to hash it see if it matches the current password then allow new password to be stored. However all that i'm getting is wrong password.

Reworked:

def change_password(oldpass, newpass)
    if valid_password?(oldpass)
        password = newpass
        save
        return true
    else
        return false
    end
end
like image 759
Sterling Duchess Avatar asked Mar 26 '13 21:03

Sterling Duchess


1 Answers

You don't need to encrypt the password yourself, if you are in the application or in Rails console.

Just update the user following way and Devise will take care of it itself.

user.password = new_password
user.save

Devise will then encrypt the password and store it. You just need to ensure that user.password_confirmation is nil. If password_confirmation is anything else, it will be matched against password.

EDIT

You can check the existing password with: user.valid_password?(old_password)

like image 111
Tomáš Dundáček Avatar answered Sep 30 '22 19:09

Tomáš Dundáček