Advertisement
Guest User

Untitled

a guest
Jul 31st, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. #---
  2. # This code is not mine, I'm just trying to understand it (its from pragprog's agile dev
  3. # with rails book)
  4. #
  5. # Newby Questions:
  6. # - This code outputs an 'undefined method hashed_password' error
  7. # (in password=(pwd)), but doesn't output any error for the self.salt assignment in
  8. # create_new_salt(), which is called before. Why is that?
  9. # - Are the self. prefexes needed? e.g. self.password ? is it usually used only do disambiguate
  10. # between an attribute and a local variable?
  11. # -
  12. #---
  13. require 'digest/sha1'
  14.  
  15.  
  16. class User < ActiveRecord::Base
  17.  
  18. validates_presence_of :name,
  19. :password
  20.  
  21. validates_uniqueness_of :name
  22.  
  23. validates_length_of :password,
  24. :minimum => 5,
  25. :message => "should be at least 5 characters long"
  26.  
  27. attr_accessor :password_confirmation
  28. validates_confirmation_of :password
  29.  
  30. # ...
  31.  
  32.  
  33.  
  34. def self.authenticate(name, password)
  35. user = self.find_by_name(name)
  36. if user
  37. expected_password = encrypted_password(password, user.salt)
  38. if user.hashed_password != expected_password
  39. user = nil
  40. end
  41. end
  42. user
  43. end
  44.  
  45.  
  46. # 'password' is a virtual attribute
  47.  
  48. def password
  49. @password
  50. end
  51.  
  52. def password=(pwd)
  53. @password = pwd
  54. create_new_salt
  55. self.hashed_password = User.encrypted_password(self.password, self.salt)
  56. end
  57.  
  58. private
  59.  
  60. def create_new_salt
  61. self.salt = self.object_id.to_s rand.to_s
  62. end
  63.  
  64. def self.encrypted_password(password, salt)
  65. string_to_hash = password "wibble" salt
  66. Digest::SHA1.hexdigest(string_to_hash)
  67. end
  68.  
  69. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement