Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'digest/sha1'
- class User < ActiveRecord::Base
- # make sure we have the required fields when saving
- validates_presence_of :user_name,
- :password,
- :password_confirmation
- # make the name unique as it is going to be the login
- validates_uniqueness_of :user_name
- # we want password to be at least 5 characters
- validates_length_of :password,
- :minimum => 5,
- :message => "should be at least 5 characters long"
- # make sure that password_confirmation and password match
- attr_accessor :password_confirmation
- validates_confirmation_of :password
- #-----------------------------------------------------------------
- # lookup the user and check the password
- # set user to nil if user doesn't exist
- # or password doesn't match
- def self.login(user_name, password)
- user = User.find(:first, :conditions => ['user_name = ?', user_name])
- if user
- expected_password = encrypted_password(password, user.password_salt)
- if user.password_hash != expected_password
- user = nil
- end
- end
- user
- 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
- #-----------------------------------------------------------------
- def safe_delete
- transaction do
- destroy
- if User.count.zero?
- raise "Can't delete last user"
- end
- end
- end
- #-----------------------------------------------------------------
- # create the salt we will use when encrypting the password
- def create_new_salt
- self.password_salt =
- [Array.new(6){rand(256).chr}.join].pack("m").chomp
- end
- #-----------------------------------------------------------------
- # returns the hash for the password using the salt provided
- 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