Guest User

Untitled

a guest
Apr 11th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. require 'test/unit'
  2.  
  3. require 'rubygems'
  4. require 'active_record'
  5. require 'bcrypt'
  6.  
  7. ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :dbfile => ":memory:")
  8.  
  9. ActiveRecord::Schema.define(:version => 1) do
  10.  
  11. create_table "passwords", :force => true do |t|
  12. t.integer "user_id"
  13. t.string "hash"
  14. t.datetime "created_at"
  15. end
  16.  
  17. create_table "users", :force => true do |t|
  18. t.string "name"
  19. t.datetime "created_at"
  20. t.datetime "updated_at"
  21. end
  22.  
  23. end
  24.  
  25. class User < ActiveRecord::Base
  26. has_one :password, :dependent => :destroy
  27. validates_presence_of :name
  28. validates_uniqueness_of :name
  29.  
  30. def self.authenticate(name, password)
  31. if user = User.find_by_name(name)
  32. user.password == password && user
  33. end
  34. end
  35. end
  36.  
  37. require 'digest/sha1'
  38.  
  39. class Password < ActiveRecord::Base
  40. belongs_to :user
  41. validates_associated :user
  42. validates_presence_of :user_id
  43. validates_uniqueness_of :user_id
  44.  
  45. validates_confirmation_of :password
  46. validates_presence_of :password
  47.  
  48. undef_method :hash
  49. delegate :==, :to => :password
  50.  
  51. def password
  52. @password ||= BCrypt::Password.new(hash)
  53. end
  54.  
  55. def password=(new_password)
  56. @password = BCrypt::Password.create(new_password)
  57. self.hash = @password
  58. end
  59.  
  60. def reset!
  61. password = Array.new(10).map { (65 + rand(58)).chr }.join
  62. save!
  63. end
  64. end
  65.  
  66. class PasswordTest < Test::Unit::TestCase
  67. def setup
  68. # Clear fixtures out of database
  69. User.delete_all
  70. Password.delete_all
  71.  
  72. @user = User.create! :name => "david"
  73. @password = @user.create_password :password => "password"
  74. end
  75.  
  76. def test_should_create_password
  77. assert @password.valid?
  78. end
  79.  
  80. def test_should_match_password
  81. assert_equal @user.password, "password"
  82. end
  83.  
  84. def test_should_authenticate_user
  85. assert_equal @user, User.authenticate("david", "password")
  86. end
  87.  
  88. def test_should_not_authenticate_user
  89. assert !User.authenticate("matz", "password")
  90. assert !User.authenticate("david", "wrong")
  91. end
  92.  
  93. def test_should_reset_password
  94. old_password = @user.password.password
  95. @user.password.reset!
  96. assert_not_equal old_password, @user.password.password
  97. end
  98. end
Add Comment
Please, Sign In to add comment