Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class User < ActiveRecord::Base
- require 'digest/sha1'
- has_many :user_stats
- #...validation stuff
- validates_presence_of :rank
- validates_presence_of :username
- validates_uniqueness_of :username
- attr_accessor :password_confirmation
- validates_confirmation_of :password
- RANKS = [
- # Displayed stored in db
- [ "Employee", "1" ],
- [ "Admin", "2" ]
- ]
- def validate
- errors.add_to_base("Missing Password") if hashed_password.blank?
- end
- def self.authenticate(username, password)
- user = self.find_by_username(username)
- if user
- expected_password = encrypted_password(password, user.salt)
- if user.hashed_password != expected_password
- user = nil
- end
- end
- user
- end
- def password
- @password
- end
- def password=(pwd)
- @password = pwd
- create_new_salt
- self.hashed_password = User.encrypted_password(self.password, self.salt)
- end
- def after_destroy
- if User.count.zero?
- raise "Can't delete last user"
- end
- end
- def location
- return user_stats.find(:first, :order => 'id DESC').location if user_stats.count > 0
- 'unknown'
- end
- def total_revenue
- user_stats.sum('gross_revenue')
- end
- private
- def self.encrypted_password(password, salt)
- string_to_hash = password + "sample" + salt # 'sample' makes it harder to guess
- Digest::SHA1.hexdigest(string_to_hash)
- end
- def create_new_salt
- self.salt = self.object_id.to_s + rand.to_s
- end
- end
Add Comment
Please, Sign In to add comment