Guest User

Untitled

a guest
Feb 19th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. module Clearance
  2. module Model
  3.  
  4. def included(base)
  5. base.class_eval do
  6.  
  7. attr_accessible :email, :password, :password_confirmation
  8. attr_accessor :password, :password_confirmation
  9.  
  10. validates_presence_of :email
  11. validates_presence_of :password, :if => :password_required?
  12. validates_length_of :password, :within => 3..40, :if => :password_required?
  13. validates_confirmation_of :password, :if => :password_required?
  14. validates_uniqueness_of :email
  15.  
  16. before_save :initialize_salt, :encrypt_password
  17.  
  18. extend ClassMethods
  19.  
  20. include InstanceMethods
  21.  
  22. protected
  23.  
  24. include ProtectedInstanceMethods
  25.  
  26. end
  27. end
  28.  
  29. module ClassMethods
  30.  
  31. def authenticate(email, password)
  32. user = find_by_email(email) # need to get the salt
  33. user && user.authenticated?(password) ? user : nil
  34. end
  35.  
  36. def authenticate_via_auth_token(token)
  37. return nil if token.blank?
  38. find_by_auth_token(token)
  39. end
  40.  
  41. end
  42.  
  43. module InstanceMethods
  44.  
  45. def authenticated?(password)
  46. crypted_password == encrypt(password)
  47. end
  48.  
  49. def encrypt(password)
  50. Digest::SHA1.hexdigest("--#{salt}--#{password}--")
  51. end
  52.  
  53. def remember_token?
  54. remember_token_expires_at && Time.now.utc < remember_token_expires_at
  55. end
  56.  
  57. def remember_me!
  58. remember_me_until 2.weeks.from_now.utc
  59. end
  60.  
  61. def remember_me_until(time)
  62. self.update_attribute :remember_token_expires_at, time
  63. self.update_attribute :remember_token, encrypt("#{email}--#{remember_token_expires_at}")
  64. end
  65.  
  66. def forget_me!
  67. self.update_attribute :remember_token_expires_at, nil
  68. self.update_attribute :remember_token, nil
  69. end
  70.  
  71. end
  72.  
  73. module ProtectedInstanceMethods
  74.  
  75. def initialize_salt
  76. self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{email}--") if new_record?
  77. end
  78.  
  79. def encrypt_password
  80. return if password.blank?
  81. self.crypted_password = encrypt(password)
  82. end
  83.  
  84. def password_required?
  85. crypted_password.blank? || !password.blank?
  86. end
  87.  
  88. end
  89.  
  90. end
  91. end
Add Comment
Please, Sign In to add comment