Class: Authentication::Authenticator

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

Overview

A object to authenticate client.

Since:

  • 0.0.2

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Authenticator

Returns a new instance of Authenticator.

Parameters:

  • options (Hash)

    the options to create a authenticator with.

Options Hash (options):

  • :session (Hash)

    Hash-like session object.

  • :session_key (Symbol)

    Key of session_id.

  • :finder (Proc)

    A proc which returns client to authenticate.

  • :after_login_callback (Proc)

    A proc which will be invoked after #login!.

  • :after_logout_callback (Proc)

    A proc which will be invoked after #logout.

Since:

  • 0.0.2



11
12
13
14
15
16
17
# File 'lib/authentication/authenticator.rb', line 11

def initialize(options)
  @session = options.fetch :session
  @session_key = options.fetch :session_key
  @finder = options.fetch :finder
   = options[:after_login_callback]
  @after_logout_callback = options[:after_logout_callback]
end

Instance Method Details

#current_clientObject Also known as: current_user

Return current_client. If it does not exist, returns nil.

Returns:

  • (Object)

    The object stored as client or nil

Since:

  • 0.0.2



33
34
35
# File 'lib/authentication/authenticator.rb', line 33

def current_client
  @current_client ||= @finder.call
end

#current_client_idObject Also known as: current_user_id

Return id of given current_client. If it does not exist, returns nil.

Returns:

  • (Object)

    The id of object stored as client or nil

Since:

  • 0.0.2



42
43
44
# File 'lib/authentication/authenticator.rb', line 42

def current_client_id
  @session[@session_key]
end

#logged_in?Boolean

Return current_client exists or not.

Returns:

  • (Boolean)

Since:

  • 0.0.2



50
51
52
# File 'lib/authentication/authenticator.rb', line 50

def logged_in?
  not current_client.nil?
end

#login!(client) ⇒ Object

Set current_client.

Raises:

Since:

  • 0.0.2



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

def login!(client)
  raise Unauthenticated unless client
  @current_client = client
  @session[@session_key] = client.id
  
end

#logout!Object

Delete current_client from database and session.

Since:

  • 0.0.2



56
57
58
59
60
# File 'lib/authentication/authenticator.rb', line 56

def logout!
  return unless current_client
  @current_client = @session[@session_key] = nil
  invoke_after_logout_callback!
end