DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Simple User Model With Password Crypting

  • submit to reddit
        A simple user model. It's using the virtual password attribute 'password' to store the clear-text password. This is what e.g. forms use for password input. It stores this password in the password_hash column. 

It allows for user editing, using the same form as user creation. The password won't be updated, and validations will pass, if the user doesn't touch the password field in the form.

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)


  # 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)

  # 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?
  # 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?


Snippets Manager replied on Tue, 2009/01/06 - 7:48am

I've wrote an article about generate random password before user has been saved Please take a look:

Snippets Manager replied on Thu, 2008/11/20 - 2:18am

witch file do i need to save it in?

Snippets Manager replied on Wed, 2007/10/31 - 4:03pm

this snippet proved super handy.. thanks for sharing