Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #---
- # This code is not mine, I'm just trying to understand it (its from pragprog's agile dev
- # with rails book)
- #
- # Newby Questions:
- # - This code outputs an 'undefined method hashed_password' error
- # (in password=(pwd)), but doesn't output any error for the self.salt assignment in
- # create_new_salt(), which is called before. Why is that?
- # - Are the self. prefexes needed? e.g. self.password ? is it usually used only do disambiguate
- # between an attribute and a local variable?
- # -
- #---
- require 'digest/sha1'
- class User < ActiveRecord::Base
- validates_presence_of :name,
- :password
- validates_uniqueness_of :name
- validates_length_of :password,
- :minimum => 5,
- :message => "should be at least 5 characters long"
- attr_accessor :password_confirmation
- validates_confirmation_of :password
- # ...
- def self.authenticate(name, password)
- user = self.find_by_name(name)
- if user
- expected_password = encrypted_password(password, user.salt)
- if user.hashed_password != expected_password
- user = nil
- end
- end
- user
- end
- # 'password' is a virtual attribute
- def password
- @password
- end
- def password=(pwd)
- @password = pwd
- create_new_salt
- self.hashed_password = User.encrypted_password(self.password, self.salt)
- end
- private
- def create_new_salt
- self.salt = self.object_id.to_s rand.to_s
- end
- def self.encrypted_password(password, salt)
- string_to_hash = password "wibble" salt
- Digest::SHA1.hexdigest(string_to_hash)
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement