Guest User

Untitled

a guest
Jul 8th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. #
  2. #CONTROLADOR
  3. #
  4.  
  5. #
  6. def add_user
  7. #
  8. @user = User.new(params[:user])
  9. #
  10. if request.post? and @user.save
  11. #
  12. flash.now[:notice] = "User #{@user.name} created"
  13. #
  14. @user = User.new
  15. #
  16. end
  17. #
  18. end
  19. #
  20.  
  21. #
  22.  
  23. #
  24.  
  25. #
  26.  
  27. #
  28. #MODELO
  29. #
  30.  
  31. #
  32. require 'digest/sha1'
  33. #
  34. class User < ActiveRecord::Base
  35. #
  36.  
  37. #
  38. validates_presence_of :name
  39. #
  40. validates_uniqueness_of :name
  41. #
  42. attr_accessor :password_confirmation
  43. #
  44. validates_confirmation_of :password
  45. #
  46.  
  47. #
  48. def validate
  49. #
  50. errors.add_to_base("Missing password") if hashed_password.blank?
  51. #
  52. end
  53. #
  54.  
  55. #
  56.  
  57. #
  58. def password
  59. #
  60. @password
  61. #
  62. end
  63. #
  64.  
  65. #
  66.  
  67. #
  68. def password=(pwd)
  69. #
  70. @password = pwd
  71. #
  72. return if pwd.blank?
  73. #
  74. create_new_salt
  75. #
  76. self.hashed_password = User.encrypted_password(self.password,self.salt)
  77. #
  78. end
  79. #
  80.  
  81. #
  82. def after_destroy
  83. #
  84. if User.count.zero?
  85. #
  86. raise "Can't delete last user"
  87. #
  88. end
  89. #
  90. end
  91. #
  92.  
  93. #
  94.  
  95. #
  96.  
  97. #
  98. def self.authenticate(name,password)
  99. #
  100. user = self.find_by_name(name)
  101. #
  102. if user
  103. #
  104. expected_password = encrypted_password(password,user.salt)
  105. #
  106. if user.hashed_password != expected_password
  107. #
  108. user = nil
  109. #
  110. end
  111. #
  112. end
  113. #
  114. user
  115. #
  116. end
  117. #
  118.  
  119. #
  120.  
  121. #
  122. private
  123. #
  124.  
  125. #
  126. def self.encrypted_password(password, salt)
  127. #
  128. string_to_hash = password + "wibble" + salt
  129. #
  130. Digest::SHA1.hexdigest(string_to_hash)
  131. #
  132. end
  133. #
  134.  
  135. #
  136.  
  137. #
  138. def create_new_salt
  139. #
  140. self.salt = self.object_id.to_s + rand.to_s
  141. #
  142. end
  143. #
  144.  
  145. #
  146. end
Add Comment
Please, Sign In to add comment