require 'digest/sha1' class Account < ActiveRecord::Base include InputSanitization attr_accessor :password_changed attr_protected :admin Default_Account_Password = '' Default_Account_Password_Hint = if Default_Account_Password.length == 0 then 'blank' else "'" + Default_Account_Password + "'" end has_many :payments, :dependent => :destroy has_many :rsvps, :dependent => :destroy has_one :company, :dependent => :destroy validates_uniqueness_of :login, :on => :create validates_confirmation_of :password validates_length_of :login, :within => 3..40 validates_format_of :login, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :message => "needs to be an email address." #validates_length_of :password, :within => 0..40 validates_presence_of :login before_create :crypt_password before_update :crypt_password # Please change the salt to something else, # Every application should use a different one @@salt = 'afwedd' cattr_accessor :salt # Authenticate a user. # # Example: # @user = User.authenticate('bob', 'bobpass') # def self.authenticate(login, pass) self.authenticate_by_token(login, hash_password(pass)) end def self.authenticate_by_token(login, token) find(:first, :conditions => ["login = ? AND password = ?", login, token]) end def self.hash_password(pass) sha1(pass) end protected # Apply SHA1 encryption to the supplied password. # We will additionally surround the password with a salt # for additional security. def self.sha1(pass) Digest::SHA1.hexdigest("#{salt}--#{pass}--") end # Before saving the record to database we will crypt the password # using SHA1. # We never store the actual password in the DB. def crypt_password if @password_changed write_attribute "password", self.class.sha1(password) end end # If the record is updated we will check if the password is empty. # If its empty we assume that the user didn't want to change his # password and just reset it to the old value. def crypt_unless_empty # This method is not used because we allow empty password. if password.empty? user = self.class.find(self.id) self.password = user.password else write_attribute "password", self.class.sha1(password) end end public def to_s name.blank? ? login : name end def write_attribute(name, *args) @password_changed = true if name == 'password' super end def owner?(user) self.id == user.id end end