Agile web development with rails

Posted by Steve on Stack Overflow See other posts from Stack Overflow or by Steve
Published on 2010-05-04T18:07:40Z Indexed on 2010/05/04 18:38 UTC
Read the original article Hit count: 169

Filed under:
|

Hi.. This code is from the agile web development with rails book.. I don't understand this part of the code... User is a model which has name,hashed_password,salt as its fields. But in the code they are mentioning about password and password confirmation, while there are no such fields in the model. Model has only hashed_password. I am sure mistake is with me. Please clear this for me :) User Model has name,hashed_password,salt. All the fields are strings

require 'digest/sha1'
class User < ActiveRecord::Base 
      validates_presence_of :name
      validates_uniqueness_of   :name
      attr_accessor :password_confirmation 
      validates_confirmation_of :password
      validate :password_non_blank

      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

      def password 
          @password
      end

      def password=(pwd) 
          @password = pwd 
          return if pwd.blank? 
          create_new_salt 
          self.hashed_password = User.encrypted_password(self.password, self.salt)
      end

      private
        def password_non_blank 
            errors.add(:password,"Missing password")if hashed_password.blank?
        end

        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

© Stack Overflow or respective owner

Related posts about ruby

Related posts about ruby-on-rails