Class: MinimalistAuthentication::Authenticator

Inherits:
Object
  • Object
show all
Defined in:
lib/minimalist_authentication/authenticator.rb

Constant Summary collapse

LOGIN_FIELDS =
%w[email username].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(field:, value:, password:) ⇒ Authenticator

Initializes a new Authenticator instance with the provided field, value, and password.



31
32
33
34
35
# File 'lib/minimalist_authentication/authenticator.rb', line 31

def initialize(field:, value:, password:)
  @field    = field
  @value    = value
  @password = password
end

Instance Attribute Details

#fieldObject (readonly)

Returns the value of attribute field.



7
8
9
# File 'lib/minimalist_authentication/authenticator.rb', line 7

def field
  @field
end

#passwordObject (readonly)

Returns the value of attribute password.



7
8
9
# File 'lib/minimalist_authentication/authenticator.rb', line 7

def password
  @password
end

#valueObject (readonly)

Returns the value of attribute value.



7
8
9
# File 'lib/minimalist_authentication/authenticator.rb', line 7

def value
  @value
end

Class Method Details

.authenticate(params) ⇒ Object

Attempts to find and authenticate a user based on the provided params. Expects a params hash with email or username and password keys. Returns user upon successful authentication. Otherwise returns nil.

Params examples: { email: ‘[email protected]’, password: ‘abc123’ } { username: ‘user’, password: ‘abc123’ }



16
17
18
19
20
# File 'lib/minimalist_authentication/authenticator.rb', line 16

def self.authenticate(params)
  hash = params.to_h.with_indifferent_access
  field, value = hash.find { |key, _| LOGIN_FIELDS.include?(key) }
  new(field:, value:, password: hash["password"]).authenticated_user
end

.authenticated_user(params) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/minimalist_authentication/authenticator.rb', line 22

def self.authenticated_user(params)
  MinimalistAuthentication.deprecator.warn(<<-MSG.squish)
    Calling MinimalistAuthentication::Authenticator.authenticated_user is deprecated.
    Use MinimalistAuthentication::Authenticator.authenticate instead.
  MSG
  authenticate(params)
end

Instance Method Details

#authenticated_userObject

Returns an authenticated and enabled user or nil.



38
39
40
# File 'lib/minimalist_authentication/authenticator.rb', line 38

def authenticated_user
  authenticated&.enabled if valid?
end