Guest User

Untitled

a guest
Feb 19th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. class User < ActiveRecord::Base
  2. attr_accessor :password
  3. attr_accessible :name, :email, :password, :password_confirmation
  4.  
  5. has_one :nutrition_profile
  6.  
  7. has_many :microposts, :dependent => :destroy
  8. has_many :relationships, :dependent => :destroy,
  9. :foreign_key => "follower_id"
  10. has_many :reverse_relationships, :dependent => :destroy,
  11. :foreign_key => "followed_id",
  12. :class_name => "Relationship"
  13. has_many :following, :through => :relationships, :source => :followed
  14. has_many :followers, :through => :reverse_relationships,
  15. :source => :follower
  16.  
  17. email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  18.  
  19. validates :name, :presence => true,
  20. :length => { :maximum => 50 }
  21. validates :email, :presence => true,
  22. :format => { :with => email_regex },
  23. :uniqueness => { :case_sensitive => false }
  24. validates :password, :presence => true,
  25. :confirmation => true,
  26. :length => { :within => 6..40 }
  27.  
  28. before_save :encrypt_password
  29.  
  30. def has_password?(submitted_password)
  31. encrypted_password == encrypt(submitted_password)
  32. end
  33.  
  34. def has_nutrition_profile?
  35. if (NutritionProfile.where(:user_id => :id).count < 1)
  36. false
  37. else
  38. true
  39. end
  40. end
  41.  
  42. def feed
  43. Micropost.from_users_followed_by(self)
  44. end
  45.  
  46. def following?(followed)
  47. relationships.find_by_followed_id(followed)
  48. end
  49.  
  50. def follow!(followed)
  51. relationships.create!(:followed_id => followed.id)
  52. end
  53.  
  54. def unfollow!(followed)
  55. relationships.find_by_followed_id(followed).destroy
  56. end
  57.  
  58. class << self
  59. def authenticate(email, submitted_password)
  60. user = find_by_email(email)
  61. (user && user.has_password?(submitted_password)) ? user : nil
  62. end
  63.  
  64. def authenticate_with_salt(id, cookie_salt)
  65. user = find_by_id(id)
  66. (user && user.salt == cookie_salt) ? user : nil
  67. end
  68. end
  69.  
  70. private
  71.  
  72. def encrypt_password
  73. self.salt = make_salt if new_record?
  74. self.encrypted_password = encrypt(password)
  75. end
  76.  
  77. def encrypt(string)
  78. secure_hash("#{salt}--#{string}")
  79. end
  80.  
  81. def make_salt
  82. secure_hash("#{Time.now.utc}--#{password}")
  83. end
  84.  
  85. def secure_hash(string)
  86. Digest::SHA2.hexdigest(string)
  87. end
  88. end
Add Comment
Please, Sign In to add comment