これは、ほとんどのタイプの認証 (および私がほとんどの場合使用するもの) にとって便利なソリューションですが、本当に has_secure_password なしで認証を記述する必要がある場合は、Ryan Bates の Railscasts を参照してください。
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation
attr_accessor :password
before_save :encrypt_password
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates_presence_of :email
validates_uniqueness_of :email
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
end
Rails 4 の場合、これは異なります (モデルに attr_accessors がなくなりました)。これを変更するには、 attr_reader :password と、パスワードと password_confirmation を設定する方法が必要です。
class User < ActiveRecord::Base
attr_reader :password
before_save :encrypt_password
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates_presence_of :email
validates_uniqueness_of :email
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
##
# accessor
def password=(unencrypted_password)
unless unencrypted_password.blank?
@password = unencrypted_password
end
end
##
# accessor
def password_confirmation=(unencrypted_password)
@password_confirmation = unencrypted_password
end
end
ただし、ここで has_secure_password メソッドを見ると、ビジネス ロジックが保存前のコールバックではなく password=(unencrypted) にあることがわかります (これは当然のことです)。