Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'test/unit'
- require 'rubygems'
- require 'active_record'
- require 'bcrypt'
- ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :dbfile => ":memory:")
- ActiveRecord::Schema.define(:version => 1) do
- create_table "passwords", :force => true do |t|
- t.integer "user_id"
- t.string "hash"
- t.datetime "created_at"
- end
- create_table "users", :force => true do |t|
- t.string "name"
- t.datetime "created_at"
- t.datetime "updated_at"
- end
- end
- class User < ActiveRecord::Base
- has_one :password, :dependent => :destroy
- validates_presence_of :name
- validates_uniqueness_of :name
- def self.authenticate(name, password)
- if user = User.find_by_name(name)
- user.password == password && user
- end
- end
- end
- require 'digest/sha1'
- class Password < ActiveRecord::Base
- belongs_to :user
- validates_associated :user
- validates_presence_of :user_id
- validates_uniqueness_of :user_id
- validates_confirmation_of :password
- validates_presence_of :password
- undef_method :hash
- delegate :==, :to => :password
- def password
- @password ||= BCrypt::Password.new(hash)
- end
- def password=(new_password)
- @password = BCrypt::Password.create(new_password)
- self.hash = @password
- end
- def reset!
- password = Array.new(10).map { (65 + rand(58)).chr }.join
- save!
- end
- end
- class PasswordTest < Test::Unit::TestCase
- def setup
- # Clear fixtures out of database
- User.delete_all
- Password.delete_all
- @user = User.create! :name => "david"
- @password = @user.create_password :password => "password"
- end
- def test_should_create_password
- assert @password.valid?
- end
- def test_should_match_password
- assert_equal @user.password, "password"
- end
- def test_should_authenticate_user
- assert_equal @user, User.authenticate("david", "password")
- end
- def test_should_not_authenticate_user
- assert !User.authenticate("matz", "password")
- assert !User.authenticate("david", "wrong")
- end
- def test_should_reset_password
- old_password = @user.password.password
- @user.password.reset!
- assert_not_equal old_password, @user.password.password
- end
- end
Add Comment
Please, Sign In to add comment