Advertisement
Guest User

Untitled

a guest
Jul 30th, 2017
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. class User < ActiveRecord::Base
  2.  
  3. require 'digest/sha2'
  4.  
  5. validates_uniqueness_of :username
  6. validates_presence_of :username
  7. validates_presence_of :password, :if => :password_required?
  8. validates_length_of :username, :within => 4..20
  9. validates_length_of :password, :minimum => 6, :if => :password_required?
  10. validates_format_of :username, :with => /^[a-zA-Z] ([a-zA-Z0-9\s]*[a-zA-Z0-9])?$/, :message => N_("must start with a letter, end with a letter or numer, and contain only letters, numbers and white spaces.")
  11. attr_accessor :password
  12. attr_protected :id, :hashed_password, :type, :salt
  13.  
  14. def password=(new_pass)
  15. if !new_pass.blank?
  16. @password = new_pass
  17. salt = [Array.new(6){rand(256).chr}.join].pack("m")[0..7]; # 2^48 combos
  18. # password_salt and password_sha1 are DB-backed AR attributes
  19. # Prefix the password with the encryption method for future evolution
  20. self.salt, self.hashed_password = salt, 'sha256:' Digest::SHA256.hexdigest(new_pass salt)
  21. end
  22. end
  23.  
  24. def password_is?(pw)
  25. case self.hashed_password.split(':').first
  26. when 'sha256' then return 'sha256:' Digest::SHA256.hexdigest(pw self.salt) == self.hashed_password
  27. else raise "Invalid Password Format"
  28. end
  29. false
  30. end
  31.  
  32. def self.authenticate(username, pw)
  33. requested_person = User.find(:first, :conditions => ["username = ?", username])
  34. if requested_person
  35. return requested_person.id if requested_person.password_is?(pw)
  36. end
  37. return false
  38. end
  39.  
  40. protected
  41.  
  42. def password_required?
  43. hashed_password.nil? || !password.blank?
  44. end
  45.  
  46. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement