How to set current_user in middleware?

To learn more about my question, refer to this Github issue - https://github.com/getsentry/raven-ruby/issues/144

I use raven , which is an error logger. I want to add an identifier for current_user if the user is logged in. The answer I received was

This should be done through your middleware or something similar.

where it means setting current_user to Raven.

I read about middlewares, but still could not figure out how I can get current_user in one.

+7
ruby-on-rails devise sentry
source share
2 answers

For Rails applications, I had success by simply setting the Raven (Sentry) context to before_action inside the ApplicationController :

 # application_controller.rb class ApplicationController < ActionController::Base before_action :set_raven_context def set_raven_context # I use subdomains in my app, but you could leave this next line out if it not relevant context = { account: request.subdomain } context.merge!({ user_id: current_user.id, email: current_user.email }) unless current_user.blank? Raven.user_context(context) end end 

This works because the Raven Rack middleware clears the context after each request. See here. However, this may not be the most effective, as you set the context even in most cases that do not result in an exception. But in any case, this is not such an expensive operation, and it will force you to be quite far away, even if you do not need to bother with the introduction of the new Rack middleware or something else.

+14
source share

I don’t have a big idea about Raven , but below is the way that we refer to the current user in a request throughout our application.

We created a class that acts like a cache and inserts / retrieves data from the current thread

 class CustomCache def self.namespace "my_application" end def self.get(res) Thread.current[self.namespace] ||= {} val = Thread.current[self.namespace][res] if val.nil? and block_given? val = yield self.set(res, val) unless val.nil? end return val end def self.set(key, value) Thread.current[self.namespace][key] = value end def self.reset Thread.current[self.namespace] = {} end end 

And then, when the request is received, a check is performed for the current session, and then the user model is inserted into the cache, as shown below

 def current_user if defined?(@current_user) return @current_user end @current_user = current_user_session && current_user_session.record CustomCache.set(:current_user, @current_user) return @current_user end 

Now you can get the current user from anywhere in your application using the following code:

 CustomCache.get(:current_user) 

We also check the reset cache before and after the request, so we do this,

 CustomCache.reset 

Hope this helps.

+1
source share

All Articles