Created
April 1, 2018 00:32
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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