Guest User

Untitled

a guest
Jul 29th, 2018
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. class User < ActiveRecord::Base
  2.  
  3. attr_accessor :password
  4.  
  5. EMAIL_REGEX = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
  6.  
  7. validates :first_name, :presence => true, :length => { :maximum => 50 }
  8. validates :last_name, :presence => true, :length => { :maximum => 50 }
  9. validates :email, :presence => true, :length => { :maximum => 100 },
  10. :format => EMAIL_REGEX, :confirmation => true
  11.  
  12. validates_length_of :password, :within => 8..25, :on => :create
  13.  
  14. validate :validates_email
  15.  
  16. def validates_email
  17. errors.add_to_base "That email address is taken" if User.find_by_email(self.email)
  18. end
  19.  
  20. before_save :create_hashed_password
  21. before_save :capitalize_names
  22. after_save :clear_password
  23.  
  24. scope :sorted_by_type, order("users.type ASC, users.last_name ASC, users.first_name ASC")
  25.  
  26. attr_protected :hashed_password, :salt
  27.  
  28.  
  29. def name
  30. "#{first_name} #{last_name}"
  31. end
  32.  
  33. def list_name
  34. "#{last_name}, #{first_name}"
  35. end
  36.  
  37. def self.authenticate(email="", password="")
  38. user = self.find_by_email(email)
  39. if user && user.password_match?(password)
  40. return user
  41. else
  42. return false
  43. end
  44. end
  45.  
  46. # The same password string with the same hash method and salt
  47. # should always generate the same hashed_password.
  48. def password_match?(password="")
  49. hashed_pass == self.class.hash_with_salt(password, salt)
  50. end
  51.  
  52. def self.make_salt(email="")
  53. Digest::SHA1.hexdigest("Use #{email} with #{Time.now} to make salt")
  54. end
  55.  
  56. def self.hash_with_salt(password="", salt="")
  57. Digest::SHA1.hexdigest("Put #{salt} on the #{password}")
  58. end
  59.  
  60. protected
  61.  
  62. def create_hashed_password
  63. unless password.blank?
  64. self.salt = self.class.make_salt(email) if salt.blank?
  65. self.hashed_pass = self.class.hash_with_salt(password, salt)
  66. end
  67. end
  68.  
  69. def clear_password
  70. self.password = nil
  71. end
  72.  
  73. def capitalize_names
  74. self.first_name = self.first_name.capitalize
  75. self.last_name = self.last_name.capitalize
  76. end
  77.  
  78.  
  79. private
  80.  
  81. def attributes_protected_by_default
  82. super - [self.class.type]
  83. end
  84. end
Add Comment
Please, Sign In to add comment