Class: Timber::Integrations::Rack::UserContext

Inherits:
Middleware
  • Object
show all
Defined in:
lib/timber/integrations/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.

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, Timber will automatically set the user context for you.

  • Devise, or any Warden based authentication strategy

  • Omniauth

  • 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

Constructor Details

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

Class Method Details

.custom_user_hashObject

Accessor method for #custom_user_hash=.



61
62
63
# File 'lib/timber/integrations/rack/user_context.rb', line 61

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. Timber does not automatically support your authentication strategy (see module level docs)

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

Examples:

Setting your own custom user context

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


52
53
54
55
56
57
58
# File 'lib/timber/integrations/rack/user_context.rb', line 52

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



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

def call(env)
  user_hash = get_user_hash(env)
  if user_hash
    context = Contexts::User.new(user_hash)
    CurrentContext.with(context) do
      @app.call(env)
    end
  else
    @app.call(env)
  end
end