Class: Logtail::Integrations::Rack::UserContext

Inherits:
Middleware
  • Object
show all
Defined in:
lib/logtail-rack/user_context.rb

Overview

Note:

This middleware is automatically inserted for frameworks we support. Such as Rails. See Frameworks for a comprehensive list.

This is a Rack middleware responsible for setting the user context. See Contexts::User for more information on the user context.

## Why a Rack middleware?

We use a Rack middleware because we want to set the user context as early as possible, and before the initial incoming request log line:

Started GET /welcome

The above log line is logged in a request middleware, before it reaches the controller.

If, for example, we set the user context in a controller, the log line above will not have the user context attached. This is because it is logged before the controller is executed. This is not ideal, and it’s why we take a middleware approach here. If for some reason you cannot identify the user at the middleware level then setting it in the controller is perfectly fine, just be aware of the above downside.

## Authentication frameworks automatically detected:

If you use any of the following authentication frameworks, Logtail will automatically set the user context for you.

  • Devise, or any Warden based authentication strategy

  • Clearance

Or, you can use your own custom authentication, see the custom_user_context class method for more details.

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Middleware

enabled=, enabled?, #initialize

Constructor Details

This class inherits a constructor from Logtail::Integrations::Rack::Middleware

Class Method Details

.custom_user_hashObject

Accessor method for #custom_user_hash=.



62
63
64
# File 'lib/logtail-rack/user_context.rb', line 62

def custom_user_hash
  @custom_user_hash
end

.custom_user_hash=(proc) ⇒ Object

The custom user context allows you to hook in and set your own custom user context. This is used in situations where either:

  1. Logtail does not automatically support your authentication strategy (see module level docs)

  2. You need to customize your authentication beyond Logtail’s defaults.

Examples:

Setting your own custom user context

Logtail::Integrations::Rack::UserContext.custom_user_hash = lambda do |rack_env|
  rack_env['my_custom_key'].user
end


53
54
55
56
57
58
59
# File 'lib/logtail-rack/user_context.rb', line 53

def custom_user_hash=(proc)
  if proc && !proc.is_a?(Proc)
    raise ArgumentError.new("The value passed to #custom_user_hash must be a Proc")
  end

  @custom_user_hash = proc
end

Instance Method Details

#call(env) ⇒ Object



67
68
69
70
71
72
73
74
75
76
# File 'lib/logtail-rack/user_context.rb', line 67

def call(env)
  user_hash = get_user_hash(env)
  if user_hash
    CurrentContext.with({user: user_hash}) do
      @app.call(env)
    end
  else
    @app.call(env)
  end
end