This repository has been archived on 2020-03-24. You can view files and clone it, but cannot push or open issues or pull requests.
quay/util/audit.py
Joseph Schorr e220b50543 Refactor auth code to be cleaner and more extensible
We move all the auth handling, serialization and deserialization into a new AuthContext interface, and then standardize a registration model for handling of specific auth context types (user, robot, token, etc).
2018-02-14 15:35:27 -05:00

68 lines
2.3 KiB
Python

import logging
import random
from urlparse import urlparse
from flask import request
from app import analytics, userevents, ip_resolver
from data import model
from auth.auth_context import get_authenticated_context, get_authenticated_user
logger = logging.getLogger(__name__)
def track_and_log(event_name, repo_obj, analytics_name=None, analytics_sample=1, **kwargs):
repo_name = repo_obj.name
namespace_name = repo_obj.namespace_name
metadata = {
'repo': repo_name,
'namespace': namespace_name,
}
metadata.update(kwargs)
# Add auth context metadata.
analytics_id = 'anonymous'
auth_context = get_authenticated_context()
if auth_context is not None:
analytics_id, context_metadata = auth_context.analytics_id_and_public_metadata()
metadata.update(context_metadata)
# Publish the user event (if applicable)
logger.debug('Checking publishing %s to the user events system', event_name)
if auth_context and auth_context.has_nonrobot_user:
logger.debug('Publishing %s to the user events system', event_name)
user_event_data = {
'action': event_name,
'repository': repo_name,
'namespace': namespace_name,
}
event = userevents.get_event(auth_context.authed_user.username)
event.publish_event_data('docker-cli', user_event_data)
# Save the action to mixpanel.
if random.random() < analytics_sample:
if analytics_name is None:
analytics_name = event_name
logger.debug('Logging the %s to Mixpanel', analytics_name)
request_parsed = urlparse(request.url_root)
extra_params = {
'repository': '%s/%s' % (namespace_name, repo_name),
'user-agent': request.user_agent.string,
'hostname': request_parsed.hostname,
}
analytics.track(analytics_id, analytics_name, extra_params)
# Add the resolved information to the metadata.
resolved_ip = ip_resolver.resolve_ip(request.remote_addr)
if resolved_ip is not None:
metadata['resolved_ip'] = resolved_ip._asdict()
# Log the action to the database.
logger.debug('Logging the %s to logs system', event_name)
model.log.log_action(event_name, namespace_name, performer=get_authenticated_user(),
ip=request.remote_addr, metadata=metadata, repository=repo_obj)
logger.debug('Track and log of %s complete', event_name)