Module: SimpleAuth::ActiveRecord::ClassMethods
- Defined in:
- lib/simple_auth/active_record.rb
Instance Method Summary collapse
-
#authenticate(credential, password) ⇒ Object
Receive a credential and a password and try to authenticate the specified user.
-
#find_by_credential(credential) ⇒ Object
Find user by its credential.
-
#find_by_credential!(credential) ⇒ Object
Find user by its credential.
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"
89 90 91 92 |
# File 'lib/simple_auth/active_record.rb', line 89 def authenticate(credential, password) record = find_by_credential(credential.to_s) record.try(:authenticate, password) end |
#find_by_credential(credential) ⇒ Object
Find user by its credential.
User.find_by_credential "[email protected]" # using e-mail
User.find_by_credential "john" # using username
59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/simple_auth/active_record.rb', line 59 def find_by_credential(credential) # Collect each attribute that should be used as credential. query = SimpleAuth::Config.credentials.each_with_object([]) do |attr_name, buffer| buffer << "#{attr_name} = :credential" end.join(" or ") # Set the scope. scope = SimpleAuth::Config.model_class.where(query, credential: credential.to_s) # Find the record using the conditions we built scope.first end |
#find_by_credential!(credential) ⇒ Object
Find user by its credential. If no user is found, raise SimpleAuth::RecordNotFound exception.
User.find_by_credential! "[email protected]"
77 78 79 80 81 |
# File 'lib/simple_auth/active_record.rb', line 77 def find_by_credential!(credential) record = find_by_credential(credential) raise SimpleAuth::RecordNotFound, "couldn't find #{SimpleAuth::Config.model} using #{credential.inspect} as credential" unless record record end |