略過內容 略過搜尋
方法
A

執行個體公開方法

authenticate_by(attributes)

給予一組屬性,使用非密碼屬性尋找記錄,然後使用密碼屬性認證該記錄。如果認證成功,傳回記錄;否則,傳回 nil

不論是否找到記錄,authenticate_by 會以密碼學方式摘要指定的密碼屬性。此行為有助於減輕基於時間的列舉攻擊,攻擊者可以在不知道密碼的情況下,判斷是否有密碼保護的記錄存在。

如果屬性組沒有包含至少一個密碼和一個非密碼屬性,會引發 ArgumentError。

範例

class User < ActiveRecord::Base
  has_secure_password
end

User.create(name: "John Doe", email: "jdoe@example.com", password: "abc123")

User.authenticate_by(email: "jdoe@example.com", password: "abc123").name # => "John Doe" (in 373.4ms)
User.authenticate_by(email: "jdoe@example.com", password: "wrong")       # => nil (in 373.9ms)
User.authenticate_by(email: "wrong@example.com", password: "abc123")     # => nil (in 373.6ms)

User.authenticate_by(email: "jdoe@example.com", password: nil) # => nil (no queries executed)
User.authenticate_by(email: "jdoe@example.com", password: "")  # => nil (no queries executed)

User.authenticate_by(email: "jdoe@example.com") # => ArgumentError
User.authenticate_by(password: "abc123")        # => ArgumentError
# File activerecord/lib/active_record/secure_password.rb, line 41
def authenticate_by(attributes)
  passwords, identifiers = attributes.to_h.partition do |name, value|
    !has_attribute?(name) && has_attribute?("#{name}_digest")
  end.map(&:to_h)

  raise ArgumentError, "One or more password arguments are required" if passwords.empty?
  raise ArgumentError, "One or more finder arguments are required" if identifiers.empty?

  return if passwords.any? { |name, value| value.nil? || value.empty? }

  if record = find_by(identifiers)
    record if passwords.count { |name, value| record.public_send(:"authenticate_#{name}", value) } == passwords.size
  else
    new(passwords)
    nil
  end
end