Merge pull request #269 from techniq/master

Capture user information when Flask-Login / Flask-Security is used
This commit is contained in:
David Cramer 2013-04-01 13:50:45 -07:00
commit 8bd666d3b8
2 changed files with 55 additions and 9 deletions

View File

@ -30,6 +30,14 @@ Additional settings for the client can be configured using ``SENTRY_<setting nam
SENTRY_DSN = 'http://public_key:secret_key@example.com/1'
SENTRY_INCLUDE_PATHS = ['myproject']
If `Flask-Login <https://pypi.python.org/pypi/Flask-Login/>`_ is used by your application (including `Flask-Security <https://pypi.python.org/pypi/Flask-Security/>`_), user information will be captured when an exception or message is captured.
By default, only the ``id`` (current_user.get_id()), ``is_authenticated``, and ``is_anonymous`` is captured for the user. If you would like additional attributes on the ``current_user`` to be captured, you can configure them using ``SENTRY_USER_ATTRS``::
class MyConfig(object):
SENTRY_USER_ATTRS = ['username', 'first_name', 'last_name', 'email']
``email`` will be captured as ``sentry.interfaces.User.email``, and any additionl attributes will be available under ``sentry.interfaces.User.data``
Usage
-----

View File

@ -2,6 +2,40 @@ import urlparse
from raven.utils.wsgi import get_headers, get_environ
from werkzeug.exceptions import ClientDisconnected
from flask import current_app
def get_user_info(request):
"""
Requires Flask-Login (https://pypi.python.org/pypi/Flask-Login/) to be installed
and setup
"""
try:
from flask_login import current_user
except ImportError:
return None
if not hasattr(current_app, 'login_manager'):
return None
if current_user.is_authenticated():
user_info = {
'is_authenticated': True,
'is_anonymous': current_user.is_anonymous(),
'id': current_user.get_id(),
}
if 'SENTRY_USER_ATTRS' in current_app.config:
for attr in current_app.config['SENTRY_USER_ATTRS']:
if hasattr(current_user, attr):
user_info[attr] = getattr(current_user, attr)
else:
user_info = {
'is_authenticated': False,
'is_anonymous': current_user.is_anonymous(),
}
return user_info
def get_data_from_request(request):
@ -12,13 +46,17 @@ def get_data_from_request(request):
except ClientDisconnected:
formdata = {}
return {
'sentry.interfaces.Http': {
'url': '%s://%s%s' % (urlparts.scheme, urlparts.netloc, urlparts.path),
'query_string': urlparts.query,
'method': request.method,
'data': formdata,
'headers': dict(get_headers(request.environ)),
'env': dict(get_environ(request.environ)),
}
result = {}
result['sentry.interfaces.User'] = get_user_info(request)
result['sentry.interfaces.Http'] = {
'url': '%s://%s%s' % (urlparts.scheme, urlparts.netloc, urlparts.path),
'query_string': urlparts.query,
'method': request.method,
'data': formdata,
'headers': dict(get_headers(request.environ)),
'env': dict(get_environ(request.environ)),
}
return result