Created
July 22, 2015 00:44
-
-
Save jessepollak/bd62bf3fa762708d9757 to your computer and use it in GitHub Desktop.
A keen.io proxy for doing super scoped keys
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
from flask import ( | |
Blueprint, | |
request, | |
current_app, | |
render_template, | |
redirect, | |
url_for, | |
session, | |
jsonify, | |
flash, | |
g, | |
json | |
) | |
import requests | |
import re | |
from common.utils import decorators | |
keen = Blueprint('keen', __name__, url_prefix='/keen') | |
WHITELISTED_QUERIES = ['count', 'count_unique'] | |
WHITELISTED_COLLECTIONS = ['Authorized'] | |
def validate_query(type=None, data=None): | |
if not type in WHITELISTED_QUERIES: | |
return False | |
if not data.get('event_collection') in WHITELISTED_COLLECTIONS: | |
return False | |
filters = data.get('filters') | |
# we look for a team filter because we want to make sure the user is | |
# only able to access that is explicitly filtered to a team that they | |
# are an administrator on | |
team_filter = None | |
for f in filters: | |
if f.get('property_name') == 'web_app.team_id': | |
team_filter = f | |
if not (team_filter and g.user.has_permission_for_team_id('analytics', team_id=team_filter.get('property_value'))): | |
return False | |
return True | |
@keen.route('/', defaults={'path': ''}, methods=['POST', 'GET']) | |
@keen.route('/<path:path>', methods=['POST', 'GET']) | |
@decorators.assert_user | |
def keen_proxy(path=None, user=None): | |
# match the path to get the query type | |
match = re.match(r'projects/PROJECT_ID/queries/(.*)', path) | |
if match: | |
query_type = match.groups(1)[0] | |
else: | |
return jsonify(error="Invalid query type") | |
if not validate_query(type=query_type, data=json.loads(request.data)): | |
return jsonify(error="Unauthorized query.") | |
keen_request_url = 'https://api.keen.io/3.0/projects/{id}/queries/{type}'.format( | |
id=current_app.config.get('KEEN_PROJECT_ID'), | |
type=query_type | |
) | |
if request.method == 'POST': | |
response = requests.post( | |
keen_request_url, | |
headers={ | |
"Authorization": current_app.config.get('KEEN_READ_KEY'), | |
"Content-Type": "application/json" | |
}, | |
data=request.data | |
) | |
return jsonify(response.json()) | |
else: | |
return jsonify(error="Invalid query method") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment