Skip to content

Instantly share code, notes, and snippets.

@danielpowell4
Created April 1, 2018 00:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielpowell4/289a2bc8e0c459c32692f046af888bc4 to your computer and use it in GitHub Desktop.
Save danielpowell4/289a2bc8e0c459c32692f046af888bc4 to your computer and use it in GitHub Desktop.
User meta tag for Ruby on Rails app. Here used to feed Honeybadger user context information through a common application pack
# securely set current_user (likely in ApplicationController.rb or similar extended concern)
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :logged_in?, :current_user
def current_user
user = User.find_by(auth_token: cookies[:auth_token]) if cookies[:auth_token] # or from something like a user_id in session
user ? user.person : NullUser.new
end
protected
def logged_in?
current_user.present?
end
end
# app/helpers/application_helper.rb
module ApplicationHelper
def user_meta_tag
tag.meta name: 'user-context', data: {
id: current_user.id,
email: current_user.email,
name: current_user.name,
role_names: current_user.role_names
}
end
end
# app/views/layouts/application.html.erb
!DOCTYPE html>
<html lang="en-us">
<head>
...
<%= user_meta_tag %>
<%= csrf_meta_tag %>
...
</head>
<body>
...
</body>
</html>
# app/javascript/lib/User.js
export default {
getContext() {
const context = document.querySelector('meta[name="user-context"]');
if (context && context instanceof window.HTMLMetaElement) {
return context.dataset;
}
return null;
},
};
# app/javascript/packs/application.js
const revision = process.env.GIT_COMMIT;
import Honeybadger from "honeybadger-js";
import User from "../lib/User";
Honeybadger.configure({
apiKey: process.env.HONEYBADGER_JS_API_KEY,
environment: process.env.NODE_ENV,
assetsUrl: process.env.WEBPACKER_ASSETS_URL,
silent: false,
ignoreErrors: false,
revision: revision,
});
const userContext = User.getContext();
if (userContext) {
Honeybadger.setContext({
user_id: userContext.id,
user_name: userContext.name,
user_email: userContext.email,
user_role_names: userContext.roleNames,
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment