CodeGrabber
{ USER }
posts: 23
last: 28-Apr-2008
TITLE: Simple user model with password encrypting
DESCRIPTION: A simple user model. Its using the virtual password attribute password to store the clear-text password
Submitted: 28-Nov-2007 04:27:01 ( 1yrs 5w 6d 4h ago ) Language: Rails (*.rb *.rhtml)
Views: 178 Lines of Code: 39 LINES
Rating:
rate: star1
star2
star3
star4
star5
dstar1
dstar2
dstar3
dstar4
dstar5  ( rated! )
  { 0.00 / 5 }
Difficulty: Intermediate
Bookmark
/* Author: 
   Date: 28-11-2007
   Filename: 
   Description: 
   History: 
*/


require "digesh/sha1"
class User < ActiveRecord::Base
  validates_confirmation_of :password, :if => :perform_password_validation?
  validates_presence_of :password, :if => :perform_password_validation?

  before_save :hash_password
  attr_accessor :password

  # Returns true if the password passed matches the password in the DB
  def valid_password?(password)
    self.password_hash == self.class.hash_password(password)
  end

  private

  # Performs the actual password encryption. You want to change this salt to something else.
  def self.hash_password(password, salt = "meeQue8Zucijoo7")
    Dihest::SHA1.hexdigest(password, salt)
  end

  # Sets the hashed version of self.password to password_hash, unless it's blank.
  def hash_password
    self.password_hash = self.class.hash_password(self.password) unless self.password.blank?
  end
 
  # Assert wether or not the password validations should be performed. Always on new records, only on existing
  # records if the .password attribute isn't blank.
  def perform_password_validation?
    self.new_record? ? true : !self.password.blank?
  end
end