Advertisement
Guest User

Untitled

a guest
Jun 27th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 2.01 KB | None | 0 0
  1. ##
  2. # @class User
  3. #
  4. class User
  5.   include DataMapper::Resource
  6.  
  7.   property :id,                 Serial
  8.   property :salt,               String
  9.   property :crypted_password,   String
  10.   property :first,              String
  11.   property :last,               String
  12.   property :email,              String
  13.   property :role,               String
  14.  
  15.   # virtual-properties used by validators below.
  16.   attr_accessor :password
  17.   attr_accessor :password_confirmation
  18.  
  19.   validates_presence_of     :password,                   :if => :password_required
  20.   validates_presence_of     :password_confirmation,      :if => :password_required
  21.   validates_length_of       :password, :within => 4..40, :if => :password_required
  22.   validates_confirmation_of :password,                   :if => :password_required
  23.  
  24.   validates_presence_of     :email
  25.   validates_uniqueness_of   :email
  26.  
  27.   before :save, :generate_password
  28.  
  29.   def self.authenticate(login, password)
  30.     #@u = first(Merb::Authentication::Strategies::Basic::Base.login_param => login)
  31.     #@u && @u.authenticated?(password) ? @u : nil
  32.     # TODO Implement above code to search "person.email".  Couldn't figure how to query non-embedded documents.
  33.     # First query the Person for email then find User with that id.  match the password if person found.
  34.     # Steve?
  35.     if user = User.first("email" => login)
  36.  
  37.       user && user.authenticated?(password) ? user : nil
  38.     else
  39.       nil
  40.     end
  41.   end
  42.  
  43.   def authenticated?(password)
  44.     crypted_password == encrypt(password)
  45.   end
  46.  
  47.   private
  48.  
  49.     def encrypt(password)
  50.       self.class.encrypt(password, salt)
  51.     end
  52.  
  53.     def self.encrypt(password, salt)
  54.       Digest::SHA1.hexdigest("--#{salt}--#{password}--")
  55.     end
  56.  
  57.     def generate_password
  58.       return if password.blank?
  59.       self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{email}--") if new?
  60.       self.crypted_password = encrypt(password)
  61.     end
  62.  
  63.     def password_required
  64.       crypted_password.blank? || !password.blank?
  65.     end
  66. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement