Module: SimpleAuth::ActiveRecord::ClassMethods

Defined in:
lib/simple_auth/active_record.rb

Instance Method Summary collapse

Instance Method Details

#authenticate(credential, password) ⇒ Object

Receive a credential and a password and try to authenticate the specified user. If the credential is valid, then an user is returned; otherwise nil is returned.

User.authenticate "johndoe", "test"
User.authenticate "[email protected]", "test"


82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/simple_auth/active_record.rb', line 82

def authenticate(credential, password)
  # Build a hash that will be passed to the finder
  options = {:conditions => [[], {}]}

  # Iterate each attribute that should be used as credential
  # and set it to the finder conditions hash
  SimpleAuth::Config.credentials.each do |attr_name|
    options[:conditions][0] << "#{attr_name} = :#{attr_name}"
    options[:conditions][1][attr_name] = credential
  end

  # Join the attributes in OR query
  options[:conditions][0] = options[:conditions][0].join(" OR ")

  # Find the record using the conditions we built
  record = SimpleAuth::Config.model_class.first(options)

  # If no record has been found
  return nil unless record

  # Compare password
  return nil unless record.password_hash == SimpleAuth::Config.crypter.call(password, record.password_salt)

  # Yay! Everything matched so return record.
  record
end