Module: LpTokenAuth::Controller

Defined in:
lib/lp_token_auth/controller.rb

Overview

LpTokenAuth::Controller contains the primary functionality of the LpTokenAuth gem. The Controller module contains the logic around setting and clearing tokens for a resource, as well as authenticating requests with a token.

Instance Method Summary collapse

Instance Method Details

#authenticate_request!(resource = :user) ⇒ Object

Retrieves and authenticates the token for the given resource

Parameters:

  • resource (Symbol, String) (defaults to: :user)

    the symbolized or stringified class of the resource

Returns:

  • (Object)

    @current_user

Raises:



31
32
33
34
# File 'lib/lp_token_auth/controller.rb', line 31

def authenticate_request!(resource=:user)
  token = get_token
  authenticate_token! token, resource
end

#authenticate_token!(token, resource = :user) ⇒ Object

Decodes the token, and finds and sets the current user

Parameters:

  • token (String)

    the token object

  • resource (Symbol, String) (defaults to: :user)

    the symbolized or stringified class of the resource

Returns:

  • (Object)

    @current_user

Raises:



41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/lp_token_auth/controller.rb', line 41

def authenticate_token!(token, resource=:user)
  begin
    decoded = LpTokenAuth.decode!(token)
    @current_user = find_lp_resource(resource, decoded)
  rescue LpTokenAuth::Error => error
    logout
    raise error
  rescue => error
    logout
    raise LpTokenAuth::Error, error
  end
end

#current_userObject

Helper method to retrieve the current user

Returns:

  • (Object)

    @current_user



56
57
58
# File 'lib/lp_token_auth/controller.rb', line 56

def current_user
  @current_user
end

#login(user, context = '') ⇒ String

Creates and sets a JWT token for a resource

Parameters:

  • user (Object)

    the resource

  • context (String) (defaults to: '')

    any contextual information necessary for authentication

Returns:

  • (String)

    encoded token



14
15
16
17
18
19
# File 'lib/lp_token_auth/controller.rb', line 14

def (user, context='')
  token = LpTokenAuth.issue_token(user.id)
  set_current_user user
  set_token token, context
  token
end

#logoutnil

Deletes the lp_auth key from the cookies hash

Returns:

  • (nil)


23
24
25
# File 'lib/lp_token_auth/controller.rb', line 23

def logout
  clear_token
end