Guest User

Untitled

a guest
Apr 9th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. require 'bcrypt'
  2.  
  3. module Ark
  4. module Mixins
  5. module BCryptUser
  6. def self.included(base)
  7. base.class_eval do
  8. attr_accessor :password, :password_confirmation
  9.  
  10. before_save :encrypt_password
  11.  
  12. field :crypted_password, :type => String, :length => 60
  13.  
  14. validates_presence_of :password, :password_confirmation, :if => proc { self.password_required? }
  15. validates_confirmation_of :password, :if => proc { self.password_required? }
  16.  
  17. extend Ark::Mixins::BCryptUser::ClassMethods
  18. include Ark::Mixins::BCryptUser::InstanceMethods
  19. end
  20. end
  21.  
  22. module ClassMethods
  23. def authenticate(username, password)
  24. puts username
  25. puts password
  26. u = User.find(username)
  27. u && u.authenticated?(password) ? u : nil
  28. end
  29. end
  30.  
  31. module InstanceMethods
  32. def authenticated?(password)
  33. bcrypt_password == password
  34. end
  35.  
  36. def bcrypt_password
  37. @bcrypt_password ||= BCrypt::Password.new(crypted_password)
  38. end
  39.  
  40. def password_required?
  41. crypted_password.blank? || !password.blank?
  42. end
  43.  
  44. def encrypt_password
  45. return if password.blank?
  46. cost = BCrypt::Engine::DEFAULT_COST
  47. self.crypted_password = BCrypt::Password.create(password, :cost => cost)
  48. end
  49. end
  50. end
  51. end
  52. end
Add Comment
Please, Sign In to add comment