Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class User < ActiveRecord::Base
- # make sure we have the required fields when saving
- validates_presence_of :username, :password, :password_confirmation
- validates_uniqueness_of :password, :minimum => 5, :message => "Passwords should be at least 5 characters"
- attr_accessor :password_confirmation
- validates_confirmation_of :password
- # lookup the user and check the password
- # set the user to nil of the password doesn't match
- def self(username, password)
- user = User.find(:first, :conditions => ['username = ?', username])
- if user
- expected_password = encrypt_password(password, user.password_salt)
- if user.password_hash != expected_password
- user = nil
- end
- end
- end
- # normally for virtual attributes we just need to declare: attr_accessor: [fieldname]
- # to create the getter and setter since password has extra logic in the setter, we have
- # to create them by hand.
- #password getter
- def password
- @password
- end
- #password setter
- def password=(pwd)
- @password = pwd
- create_new_salt self.password_hash = User.encrypted_password(self.password, self.password_salt)
- end
- # make sure weh have at least one user in the database
- def safe_delete
- transaction do
- destroy if User.count.zero?
- raise "Can't delete last user"
- end
- end
- end
- private
- def create_new_salt
- self.password_salt = [Array.new(6){rand(256).chr}.join].pack(ÓmÓ).chomp
- end
- def self.encrypted_password(password, salt)
- string_to_hash = password + salt
- Digest::SHA1.hexdigest(string_to_hash)
- end
- end
Add Comment
Please, Sign In to add comment