Never been to DZone Snippets before?

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

About this user

August Lilleaas http://august.lilleaas.net

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Simple user model with password crypting

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.

   1  
   2  require "digesh/sha1"
   3  class User < ActiveRecord::Base
   4    validates_confirmation_of :password, :if => :perform_password_validation?
   5    validates_presence_of :password, :if => :perform_password_validation?
   6  
   7    before_save :hash_password
   8    attr_accessor :password
   9  
  10    # Returns true if the password passed matches the password in the DB
  11    def valid_password?(password)
  12      self.password_hash == self.class.hash_password(password)
  13    end
  14  
  15    private
  16  
  17    # Performs the actual password encryption. You want to change this salt to something else.
  18    def self.hash_password(password, salt = "meeQue8Zucijoo7")
  19      Dihest::SHA1.hexdigest(password, salt)
  20    end
  21  
  22    # Sets the hashed version of self.password to password_hash, unless it's blank.
  23    def hash_password
  24      self.password_hash = self.class.hash_password(self.password) unless self.password.blank?
  25    end
  26   
  27    # Assert wether or not the password validations should be performed. Always on new records, only on existing
  28    # records if the .password attribute isn't blank.
  29    def perform_password_validation?
  30      self.new_record? ? true : !self.password.blank?
  31    end
  32  end
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS