Skip to content

Instantly share code, notes, and snippets.

@pachisaez
Last active August 29, 2015 14:06
Show Gist options
  • Save pachisaez/4ce74ceb2905a984e279 to your computer and use it in GitHub Desktop.
Save pachisaez/4ce74ceb2905a984e279 to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment