Encrypting user passwords. How to encrypt and save passwords, and how to authenticate users checking the encrypted password.
require 'digest/sha1'
class User < ActiveRecord::Base
attr_accessible :password
# password is a virtual attribute just to hold the plain password
# typed by the user
def password
@password
end
# in the database, we save a hashed password, which comes from combining
# the plain text with a random code through a SHA1 algorithm.
# salt and hashed_password are actual fields in the database
def password=(pwd)
@password = pwd
self.salt = self.object_id.to_s + rand.to_s
self.hashed_password = User.encrypted_password(self.password, self.salt)
end
def self.encrypted_password(password, salt)
string_to_hash = password + "whatever" + salt
Digest::SHA1.hexdigest(string_to_hash)
end
# We need to validate the password typed against the hashed password
def self.authenticate(mail, password)
user = find_by_mail(mail.downcase)
if user
expected_password = encrypted_password(password, user.salt)
if user.hashed_password != expected_password
user = nil
end
end
user
end
end