Guest User

Untitled

a guest
Mar 4th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. require 'digest/sha1'
  2.  
  3. class User < ActiveRecord::Base
  4. attr_accessor :new_password
  5.  
  6. validates_presence_of :name
  7. validates_presence_of :email
  8. validates_uniqueness_of :email
  9.  
  10. validates_presence_of :new_password, :if => :password_required?
  11. validates_presence_of :new_password_confirmation, :if => :password_required?
  12. validates_confirmation_of :new_password, :if => :password_required?
  13.  
  14. has_url_name
  15.  
  16. # Users are authenticated with an email/password combination
  17. # by default
  18. def self.authenticate(email, password)
  19. user = self.find(:first, :conditions => ["lower(email) = lower(?)", email])
  20. return nil if user.nil?
  21. user if user.password == encrypt(password, user.salt)
  22. end
  23.  
  24. def to_param
  25. url_name
  26. end
  27.  
  28. def self.find_by_param(*args)
  29. find_by_url_name *args
  30. end
  31.  
  32.  
  33. def remember_me
  34. self.remember_token_expires_at = 2.weeks.from_now.utc
  35. self.remember_token = encrypt("#{email}--#{remember_token_expires_at}")
  36. save(false)
  37. end
  38.  
  39. def forget_me
  40. self.remember_token_expires_at = nil
  41. self.remember_token = nil
  42. save(false)
  43. end
  44.  
  45.  
  46. # Encrypts the password with the user salt
  47. def encrypt(password)
  48. self.class.encrypt(password, salt)
  49. end
  50.  
  51. def self.encrypt(password, salt)
  52. Digest::SHA1.hexdigest("#{salt}#{password}")
  53. end
  54.  
  55. protected
  56.  
  57. def before_validation_with_password_hashing
  58. return unless password_required?
  59. self.salt = generate_salt
  60. self.password = encrypt(new_password)
  61. end
  62. alias_method_chain :before_validation, :password_hashing
  63.  
  64. def before_create_with_salt_generation
  65. unless self.salt && self.salt.size == 10
  66. self.salt = generate_salt
  67. end
  68. before_create_without_salt_generation
  69. end
  70. alias_method_chain :before_create, :salt_generation
  71.  
  72.  
  73. def generate_salt
  74. chars = ('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a
  75. s = []
  76. 10.times{ s << chars[rand(chars.size)] }
  77. return s.join
  78. end
  79.  
  80. def password_required?
  81. !new_password.blank?
  82. end
  83. end
Add Comment
Please, Sign In to add comment