2012-11-06 20:27:55 +01:00
|
|
|
from django.views.decorators.csrf import csrf_exempt
|
2012-11-20 00:10:37 +01:00
|
|
|
from django.views.decorators.http import require_POST
|
2012-11-08 23:02:16 +01:00
|
|
|
from zephyr.models import UserProfile, UserActivity, get_client
|
2012-11-06 20:27:55 +01:00
|
|
|
from zephyr.lib.response import json_success, json_error
|
2012-11-08 23:02:16 +01:00
|
|
|
from django.utils.timezone import now
|
2012-11-27 00:29:50 +01:00
|
|
|
from django.db import transaction, IntegrityError
|
2012-11-28 05:37:13 +01:00
|
|
|
from django.conf import settings
|
2013-01-08 17:44:22 +01:00
|
|
|
import simplejson
|
2013-01-09 22:45:23 +01:00
|
|
|
from zephyr.lib.cache import cache_with_key
|
2013-01-11 21:16:42 +01:00
|
|
|
from zephyr.lib.queue import SimpleQueue
|
|
|
|
from zephyr.lib.timestamp import datetime_to_timestamp
|
2012-11-06 20:27:55 +01:00
|
|
|
|
2012-11-02 00:23:26 +01:00
|
|
|
from functools import wraps
|
|
|
|
|
2012-11-28 06:16:28 +01:00
|
|
|
class _RespondAsynchronously(object):
|
|
|
|
pass
|
2012-08-28 22:56:21 +02:00
|
|
|
|
2012-11-28 06:16:28 +01:00
|
|
|
# Return RespondAsynchronously from an @asynchronous view if the
|
|
|
|
# response will be provided later by calling handler.finish(), or has
|
|
|
|
# already been provided this way. We use this for longpolling mode.
|
|
|
|
RespondAsynchronously = _RespondAsynchronously()
|
2012-08-28 22:56:21 +02:00
|
|
|
|
|
|
|
def asynchronous(method):
|
2012-11-02 00:23:26 +01:00
|
|
|
@wraps(method)
|
2012-08-28 22:56:21 +02:00
|
|
|
def wrapper(request, *args, **kwargs):
|
2012-11-28 06:16:28 +01:00
|
|
|
return method(request, handler=request._tornado_handler, *args, **kwargs)
|
2012-10-27 23:56:01 +02:00
|
|
|
if getattr(method, 'csrf_exempt', False):
|
|
|
|
wrapper.csrf_exempt = True
|
2012-08-28 22:56:21 +02:00
|
|
|
return wrapper
|
2012-11-06 20:27:55 +01:00
|
|
|
|
2013-01-11 21:16:42 +01:00
|
|
|
activity_queue = SimpleQueue()
|
|
|
|
def update_user_activity(request, user_profile, client):
|
|
|
|
event={'query': request.META["PATH_INFO"],
|
|
|
|
'user_profile_id': user_profile.id,
|
|
|
|
'time': datetime_to_timestamp(now()),
|
|
|
|
'client': client.name}
|
|
|
|
if not settings.USING_RABBITMQ:
|
|
|
|
# Don't try to publish messages to rabbitmq if we're not using
|
|
|
|
# it. UserActivity updates aren't really important for most
|
|
|
|
# local development, so skipping publishing them here is
|
|
|
|
# reasonable.
|
|
|
|
return
|
|
|
|
activity_queue.json_publish("user_activity", event)
|
|
|
|
|
2012-11-20 00:10:37 +01:00
|
|
|
# I like the all-lowercase name better
|
|
|
|
require_post = require_POST
|
2012-11-06 20:27:55 +01:00
|
|
|
|
2013-01-09 22:45:23 +01:00
|
|
|
@cache_with_key(lambda user_profile_id: 'tornado_user_profile:%d' % (user_profile_id,))
|
|
|
|
def get_tornado_user_profile(user_id):
|
|
|
|
return UserProfile.objects.select_related().get(user_id=user_id)
|
|
|
|
|
|
|
|
@cache_with_key(lambda email: 'tornado_user_profile_email:%s' % (email,))
|
|
|
|
def get_tornado_user_profile_by_email(email):
|
|
|
|
return UserProfile.objects.select_related().get(user__email=email)
|
|
|
|
|
2012-11-06 20:27:55 +01:00
|
|
|
# authenticated_api_view will add the authenticated user's user_profile to
|
|
|
|
# the view function's arguments list, since we have to look it up
|
|
|
|
# anyway.
|
|
|
|
def authenticated_api_view(view_func):
|
|
|
|
@csrf_exempt
|
|
|
|
@require_post
|
2012-11-14 19:45:13 +01:00
|
|
|
@has_request_variables
|
2012-11-06 20:27:55 +01:00
|
|
|
@wraps(view_func)
|
2012-11-14 19:45:13 +01:00
|
|
|
def _wrapped_view_func(request, email=POST, api_key=POST('api-key'),
|
2012-11-28 21:15:50 +01:00
|
|
|
client=POST(default=get_client("API"), converter=get_client),
|
2012-11-14 19:45:13 +01:00
|
|
|
*args, **kwargs):
|
2012-11-06 20:27:55 +01:00
|
|
|
try:
|
2013-01-09 22:45:23 +01:00
|
|
|
if settings.RUNNING_INSIDE_TORNADO:
|
|
|
|
# Get the UserProfile from a cache because we aren't accessing
|
|
|
|
# any mutable fields (just ids plus the realm.domain)
|
|
|
|
user_profile = get_tornado_user_profile_by_email(email)
|
|
|
|
else:
|
|
|
|
user_profile = UserProfile.objects.select_related().get(user__email=email)
|
2012-11-06 20:27:55 +01:00
|
|
|
except UserProfile.DoesNotExist:
|
2012-11-14 19:43:32 +01:00
|
|
|
return json_error("Invalid user: %s" % (email,))
|
|
|
|
if api_key != user_profile.api_key:
|
|
|
|
return json_error("Invalid API key for user '%s'" % (email,))
|
2012-11-28 21:15:50 +01:00
|
|
|
request._client = client
|
2013-02-05 20:34:16 +01:00
|
|
|
request._email = email
|
2012-11-28 21:15:50 +01:00
|
|
|
update_user_activity(request, user_profile, client)
|
2012-11-06 20:27:55 +01:00
|
|
|
return view_func(request, user_profile, *args, **kwargs)
|
|
|
|
return _wrapped_view_func
|
|
|
|
|
2012-12-02 20:51:51 +01:00
|
|
|
def authenticate_log_and_execute_json(request, client, view_func, *args, **kwargs):
|
|
|
|
if not request.user.is_authenticated():
|
|
|
|
return json_error("Not logged in", status=401)
|
|
|
|
request._client = client
|
2013-01-09 22:45:23 +01:00
|
|
|
if settings.RUNNING_INSIDE_TORNADO:
|
|
|
|
# Get the UserProfile from a cache because we aren't accessing
|
|
|
|
# any mutable fields (just ids plus the realm.domain)
|
|
|
|
user_profile = get_tornado_user_profile(request.user.id)
|
|
|
|
else:
|
|
|
|
user_profile = UserProfile.objects.select_related().get(user=request.user)
|
2013-02-05 20:34:16 +01:00
|
|
|
request._email = user_profile.user.email
|
2012-12-02 20:51:51 +01:00
|
|
|
update_user_activity(request, user_profile, client)
|
|
|
|
return view_func(request, user_profile, *args, **kwargs)
|
|
|
|
|
2012-11-06 20:27:55 +01:00
|
|
|
# Checks if the request is a POST request and that the user is logged
|
|
|
|
# in. If not, return an error (the @login_required behavior of
|
|
|
|
# redirecting to a login page doesn't make sense for json views)
|
2012-12-02 20:51:51 +01:00
|
|
|
def authenticated_json_post_view(view_func):
|
2012-11-06 20:27:55 +01:00
|
|
|
@require_post
|
2012-11-28 21:15:50 +01:00
|
|
|
@has_request_variables
|
2012-11-06 20:27:55 +01:00
|
|
|
@wraps(view_func)
|
2012-11-28 21:15:50 +01:00
|
|
|
def _wrapped_view_func(request,
|
|
|
|
client=POST(default=get_client("website"), converter=get_client),
|
|
|
|
*args, **kwargs):
|
2012-12-02 20:51:51 +01:00
|
|
|
return authenticate_log_and_execute_json(request, client, view_func, *args, **kwargs)
|
|
|
|
return _wrapped_view_func
|
|
|
|
|
|
|
|
def authenticated_json_view(view_func):
|
|
|
|
@wraps(view_func)
|
|
|
|
def _wrapped_view_func(request,
|
|
|
|
client=get_client("website"),
|
|
|
|
*args, **kwargs):
|
|
|
|
return authenticate_log_and_execute_json(request, client, view_func, *args, **kwargs)
|
2012-11-06 20:27:55 +01:00
|
|
|
return _wrapped_view_func
|
2012-11-01 23:21:12 +01:00
|
|
|
|
2012-11-28 05:37:13 +01:00
|
|
|
# These views are used by the main Django server to notify the Tornado server
|
|
|
|
# of events. We protect them from the outside world by checking a shared
|
|
|
|
# secret, and also the originating IP (for now).
|
|
|
|
def authenticate_notify(request):
|
|
|
|
return (request.META['REMOTE_ADDR'] in ('127.0.0.1', '::1')
|
|
|
|
and request.POST.get('secret') == settings.SHARED_SECRET)
|
|
|
|
|
|
|
|
def internal_notify_view(view_func):
|
|
|
|
@csrf_exempt
|
|
|
|
@require_post
|
|
|
|
@wraps(view_func)
|
|
|
|
def _wrapped_view_func(request, *args, **kwargs):
|
|
|
|
if not authenticate_notify(request):
|
|
|
|
return json_error('Access denied', status=403)
|
2012-11-28 05:55:59 +01:00
|
|
|
if not hasattr(request, '_tornado_handler'):
|
|
|
|
# We got called through the non-Tornado server somehow.
|
|
|
|
# This is not a security check; it's an internal assertion
|
|
|
|
# to help us find bugs.
|
|
|
|
raise RuntimeError, 'notify view called with no Tornado handler'
|
2012-11-28 05:37:13 +01:00
|
|
|
return view_func(request, *args, **kwargs)
|
|
|
|
return _wrapped_view_func
|
|
|
|
|
2013-01-09 19:46:30 +01:00
|
|
|
class JsonableError(Exception):
|
|
|
|
def __init__(self, error):
|
|
|
|
self.error = error
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.to_json_error_msg()
|
|
|
|
|
|
|
|
def to_json_error_msg(self):
|
|
|
|
return self.error
|
|
|
|
|
|
|
|
class RequestVariableMissingError(JsonableError):
|
2012-12-19 20:19:46 +01:00
|
|
|
def __init__(self, var_name):
|
|
|
|
self.var_name = var_name
|
|
|
|
|
|
|
|
def to_json_error_msg(self):
|
|
|
|
return "Missing '%s' argument" % (self.var_name,)
|
|
|
|
|
2013-01-09 19:46:30 +01:00
|
|
|
class RequestVariableConversionError(JsonableError):
|
2012-12-19 20:19:46 +01:00
|
|
|
def __init__(self, var_name, bad_value):
|
|
|
|
self.var_name = var_name
|
|
|
|
self.bad_value = bad_value
|
|
|
|
|
|
|
|
def to_json_error_msg(self):
|
|
|
|
return "Bad value for '%s': %s" % (self.var_name, self.bad_value)
|
|
|
|
|
2012-11-01 23:21:12 +01:00
|
|
|
# Used in conjunction with @has_request_variables, below
|
|
|
|
class POST(object):
|
|
|
|
# NotSpecified is a sentinel value for determining whether a
|
|
|
|
# default value was specified for a request variable. We can't
|
|
|
|
# use None because that could be a valid, user-specified default
|
|
|
|
class _NotSpecified(object):
|
|
|
|
pass
|
|
|
|
NotSpecified = _NotSpecified()
|
|
|
|
|
|
|
|
def __init__(self, whence=None, converter=None, default=NotSpecified):
|
|
|
|
"""
|
|
|
|
whence: the name of the request variable that should be used
|
|
|
|
for this parameter. Defaults to a request variable of the
|
|
|
|
same name as the parameter.
|
|
|
|
|
|
|
|
converter: a function that takes a string and returns a new
|
|
|
|
value. If specified, this will be called on the request
|
|
|
|
variable value before passing to the function
|
|
|
|
|
|
|
|
default: a value to be used for the argument if the parameter
|
|
|
|
is missing in the request
|
|
|
|
"""
|
|
|
|
|
|
|
|
self.post_var_name = whence
|
|
|
|
self.func_var_name = None
|
|
|
|
self.converter = converter
|
|
|
|
self.default = default
|
|
|
|
|
|
|
|
# Extracts variables from the request object and passes them as
|
|
|
|
# named function arguments. The request object must be the first
|
|
|
|
# argument to the function.
|
|
|
|
#
|
|
|
|
# To use, assign a function parameter a default value that is an
|
|
|
|
# instance of the POST class. That paramter will then be
|
|
|
|
# automatically populated from the HTTP request. The request object
|
|
|
|
# must be the first argument to the decorated function.
|
2012-11-08 22:30:39 +01:00
|
|
|
#
|
2012-12-21 23:03:43 +01:00
|
|
|
# This should generally be the innermost (syntactically bottommost)
|
|
|
|
# decorator applied to a view, since other decorators won't preserve
|
|
|
|
# the default parameter values used by has_request_variables.
|
|
|
|
#
|
2012-11-08 22:30:39 +01:00
|
|
|
# Note that this can't be used in helper functions which are not
|
|
|
|
# expected to call json_error or json_success, as it uses json_error
|
|
|
|
# internally when it encounters an error
|
2012-11-01 23:21:12 +01:00
|
|
|
def has_request_variables(view_func):
|
|
|
|
num_params = view_func.func_code.co_argcount
|
|
|
|
if view_func.func_defaults is None:
|
|
|
|
num_default_params = 0
|
|
|
|
else:
|
|
|
|
num_default_params = len(view_func.func_defaults)
|
|
|
|
default_param_names = view_func.func_code.co_varnames[num_params - num_default_params:]
|
|
|
|
default_param_values = view_func.func_defaults
|
|
|
|
|
|
|
|
post_params = []
|
|
|
|
|
|
|
|
for (name, value) in zip(default_param_names, default_param_values):
|
|
|
|
if isinstance(value, POST):
|
|
|
|
value.func_var_name = name
|
|
|
|
if value.post_var_name is None:
|
|
|
|
value.post_var_name = name
|
|
|
|
post_params.append(value)
|
|
|
|
elif value == POST:
|
|
|
|
# If the function definition does not actually
|
|
|
|
# instantiate a POST object but instead uses the POST
|
|
|
|
# class itself as a value, we instantiate it as a
|
|
|
|
# convenience
|
|
|
|
post_var = POST(name)
|
|
|
|
post_var.func_var_name = name
|
|
|
|
post_params.append(post_var)
|
|
|
|
|
|
|
|
@wraps(view_func)
|
|
|
|
def _wrapped_view_func(request, *args, **kwargs):
|
|
|
|
for param in post_params:
|
2012-11-27 00:37:40 +01:00
|
|
|
if param.func_var_name in kwargs:
|
|
|
|
continue
|
|
|
|
|
2012-11-09 17:52:44 +01:00
|
|
|
default_assigned = False
|
2012-11-01 23:21:12 +01:00
|
|
|
try:
|
|
|
|
val = request.POST[param.post_var_name]
|
|
|
|
except KeyError:
|
|
|
|
if param.default is POST.NotSpecified:
|
2012-12-19 20:19:46 +01:00
|
|
|
raise RequestVariableMissingError(param.post_var_name)
|
2012-11-01 23:21:12 +01:00
|
|
|
val = param.default
|
2012-11-09 17:52:44 +01:00
|
|
|
default_assigned = True
|
2012-11-01 23:21:12 +01:00
|
|
|
|
2012-11-09 17:52:44 +01:00
|
|
|
if param.converter is not None and not default_assigned:
|
2012-11-01 23:21:12 +01:00
|
|
|
try:
|
|
|
|
val = param.converter(val)
|
|
|
|
except:
|
2012-12-19 20:19:46 +01:00
|
|
|
raise RequestVariableConversionError(param.post_var_name, val)
|
2012-11-01 23:21:12 +01:00
|
|
|
kwargs[param.func_var_name] = val
|
|
|
|
|
|
|
|
return view_func(request, *args, **kwargs)
|
|
|
|
|
|
|
|
return _wrapped_view_func
|
2013-01-08 17:44:22 +01:00
|
|
|
|
|
|
|
# Converter functions for use with has_request_variables
|
|
|
|
def to_non_negative_int(x):
|
|
|
|
x = int(x)
|
|
|
|
if x < 0:
|
|
|
|
raise ValueError("argument is negative")
|
|
|
|
return x
|
|
|
|
|
2013-01-31 21:11:51 +01:00
|
|
|
def json_to_foo(json, type):
|
2013-01-08 17:44:22 +01:00
|
|
|
data = simplejson.loads(json)
|
2013-01-31 21:11:51 +01:00
|
|
|
if not isinstance(data, type):
|
|
|
|
raise ValueError("argument is not a %s" % (type().__class__.__name__))
|
2013-01-08 17:44:22 +01:00
|
|
|
return data
|
|
|
|
|
2013-01-31 21:11:51 +01:00
|
|
|
def json_to_dict(json):
|
|
|
|
return json_to_foo(json, dict)
|
|
|
|
|
2013-01-08 17:44:22 +01:00
|
|
|
def json_to_list(json):
|
2013-01-31 21:11:51 +01:00
|
|
|
return json_to_foo(json, list)
|
|
|
|
|
|
|
|
def json_to_bool(json):
|
|
|
|
return json_to_foo(json, bool)
|