Guest User

Untitled

a guest
Mar 5th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. require 'digest/sha1'
  2.  
  3.  
  4. class User < ActiveRecord::Base
  5.  
  6.  
  7. # make sure we have the required fields when saving
  8. validates_presence_of :user_name,
  9. :password,
  10. :password_confirmation
  11. # make the name unique as it is going to be the login
  12. validates_uniqueness_of :user_name
  13.  
  14. # we want password to be at least 5 characters
  15. validates_length_of :password,
  16. :minimum => 5,
  17. :message => "should be at least 5 characters long"
  18.  
  19.  
  20. # make sure that password_confirmation and password match
  21. attr_accessor :password_confirmation
  22. validates_confirmation_of :password
  23.  
  24. #-----------------------------------------------------------------
  25. # lookup the user and check the password
  26. # set user to nil if user doesn't exist
  27. # or password doesn't match
  28.  
  29. def self.login(user_name, password)
  30.  
  31. user = User.find(:first, :conditions => ['user_name = ?', user_name])
  32. if user
  33. expected_password = encrypted_password(password, user.password_salt)
  34. if user.password_hash != expected_password
  35. user = nil
  36. end
  37. end
  38. user
  39. end
  40.  
  41. #-----------------------------------------------------------------
  42. # normally for virtual attributes we
  43. # just need to declare:
  44. # attr_accessor: [fieldname]
  45. # to create the getter and setter
  46. # since password has extra logic in
  47. # the setter, we have to create them
  48. # by hand
  49.  
  50. # password getter
  51. def password
  52. @password
  53. end
  54.  
  55. #-----------------------------------------------------------------
  56.  
  57. # password setter
  58. def password=(pwd)
  59. @password = pwd
  60. create_new_salt
  61. self.password_hash =
  62. User.encrypted_password(self.password, self.password_salt)
  63. end
  64.  
  65.  
  66. #-----------------------------------------------------------------
  67.  
  68. def safe_delete
  69.  
  70. transaction do
  71. destroy
  72. if User.count.zero?
  73. raise "Can't delete last user"
  74. end
  75. end
  76. end
  77.  
  78. #-----------------------------------------------------------------
  79.  
  80. # create the salt we will use when encrypting the password
  81.  
  82. def create_new_salt
  83. self.password_salt =
  84. [Array.new(6){rand(256).chr}.join].pack("m").chomp
  85. end
  86.  
  87. #-----------------------------------------------------------------
  88.  
  89. # returns the hash for the password using the salt provided
  90. def self.encrypted_password(password, salt)
  91. string_to_hash = password + salt
  92. Digest::SHA1.hexdigest(string_to_hash)
  93. end
  94.  
  95. end
Add Comment
Please, Sign In to add comment