Guest User

Untitled

a guest
Mar 5th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. class User < ActiveRecord::Base
  2. require 'digest/sha1'
  3.  
  4. has_many :user_stats
  5.  
  6. #...validation stuff
  7.  
  8. validates_presence_of :rank
  9. validates_presence_of :username
  10. validates_uniqueness_of :username
  11.  
  12. attr_accessor :password_confirmation
  13. validates_confirmation_of :password
  14.  
  15. RANKS = [
  16. # Displayed stored in db
  17. [ "Employee", "1" ],
  18. [ "Admin", "2" ]
  19. ]
  20.  
  21. def validate
  22. errors.add_to_base("Missing Password") if hashed_password.blank?
  23. end
  24.  
  25. def self.authenticate(username, password)
  26. user = self.find_by_username(username)
  27. if user
  28. expected_password = encrypted_password(password, user.salt)
  29. if user.hashed_password != expected_password
  30. user = nil
  31. end
  32. end
  33. user
  34. end
  35.  
  36. def password
  37. @password
  38. end
  39.  
  40. def password=(pwd)
  41. @password = pwd
  42. create_new_salt
  43. self.hashed_password = User.encrypted_password(self.password, self.salt)
  44. end
  45.  
  46. def after_destroy
  47. if User.count.zero?
  48. raise "Can't delete last user"
  49. end
  50. end
  51.  
  52. def location
  53. return user_stats.find(:first, :order => 'id DESC').location if user_stats.count > 0
  54. 'unknown'
  55. end
  56.  
  57. def total_revenue
  58. user_stats.sum('gross_revenue')
  59. end
  60.  
  61. private
  62.  
  63. def self.encrypted_password(password, salt)
  64. string_to_hash = password + "sample" + salt # 'sample' makes it harder to guess
  65. Digest::SHA1.hexdigest(string_to_hash)
  66. end
  67.  
  68. def create_new_salt
  69. self.salt = self.object_id.to_s + rand.to_s
  70. end
  71.  
  72. end
Add Comment
Please, Sign In to add comment