0

私は検証スキームを実装しており、bcrypt-ruby gem を使用しています。

require 'bcrypt'

    class User < ActiveRecord::Base

      include BCrypt

      attr_accessor :password

      attr_accessible :name, :email, :password, :password_confirmation

      validates :password, :presence => true, :on => :create,
                           :confirmation => true,
                           :length => {:within => 6..12}

     before_save :encrypt_password

      def has_password?(submitted_password)
      self.encrypted_password == submitted_password # this calls a method in bcrypt    

    # File lib/bcrypt.rb, line 171
    #     def ==(secret)
    #       super(BCrypt::Engine.hash_secret(secret, @salt))
    #     end

      end

    private

      def encrypt_password

           self.encrypted_password = Password.create(password, :cost => 5)  
       end
    end

コンソールで新しいユーザーを作成します

>> user = User.create!(:name => "test", :email => "test@test.com", :password => "foobar", :password_confirmation => "foobar")

=> #<User id: 1, name: "test", email: "test@test.com", created_at: "2011-06-23 05:00:00", updated_at: "2011-06-23 05:00:00", encrypted_password: "$2a$10$I7Wy8NDMeVcNgOsE3J/ZyubiNAESyxA7Z49H4p1x5xxH...">

そして、パスワードが有効かどうかを確認したら、次のことを行います。

>> user.has_password?("foobar")
=> true

しかし、データベースからユーザーを取得すると失敗します:

user = User.find(1)
user.has_password?("foobar")
=> false

なぜそれが起こるのですか? また、これを機能させるために bcrypt を実装するにはどうすればよいですか?

前もって感謝します。

4

2 に答える 2

0

encrypted_pa​​ssword は BCrypt::Password ではなく文字列としてデータベースに格納されているため、BCrypt の == ではなく、文字列の == を呼び出していると思います。文字列ハッシュ値の周りにパスワードのインスタンスをインスタンス化する必要があります。それは私が見たいところです。

于 2011-06-23T06:01:20.033 に答える