2013-04-23 18:51:17 +02:00
|
|
|
from __future__ import absolute_import
|
|
|
|
|
2013-10-22 15:39:39 +02:00
|
|
|
from django.http import HttpResponseRedirect
|
|
|
|
from django.contrib.auth.decorators import login_required
|
2012-11-06 20:27:55 +01:00
|
|
|
from django.views.decorators.csrf import csrf_exempt
|
2013-11-08 02:02:48 +01:00
|
|
|
from django.http import QueryDict, HttpResponseNotAllowed
|
2013-03-21 20:18:44 +01:00
|
|
|
from django.http.multipartparser import MultiPartParser
|
2013-07-29 23:03:31 +02:00
|
|
|
from zerver.models import UserProfile, get_client, get_user_profile_by_email
|
|
|
|
from zerver.lib.response import json_error, json_unauthorized
|
2012-11-08 23:02:16 +01:00
|
|
|
from django.utils.timezone import now
|
2012-11-28 05:37:13 +01:00
|
|
|
from django.conf import settings
|
2013-06-18 23:55:55 +02:00
|
|
|
import ujson
|
2013-03-21 20:18:44 +01:00
|
|
|
from StringIO import StringIO
|
2013-07-29 23:03:31 +02:00
|
|
|
from zerver.lib.queue import queue_json_publish
|
|
|
|
from zerver.lib.timestamp import datetime_to_timestamp
|
|
|
|
from zerver.lib.utils import statsd
|
|
|
|
from zerver.exceptions import RateLimited
|
|
|
|
from zerver.lib.rate_limiter import incr_ratelimit, is_ratelimited, \
|
2013-05-29 23:58:07 +02:00
|
|
|
api_calls_left
|
2013-10-17 16:33:04 +02:00
|
|
|
|
2012-11-02 00:23:26 +01:00
|
|
|
from functools import wraps
|
2013-03-21 20:15:27 +01:00
|
|
|
import base64
|
2013-05-29 23:58:07 +02:00
|
|
|
import logging
|
2013-07-02 17:30:04 +02:00
|
|
|
import cProfile
|
2013-10-07 17:35:22 +02:00
|
|
|
from zerver.lib.mandrill_client import get_mandrill_client
|
2013-04-16 22:52:32 +02:00
|
|
|
|
2013-11-12 23:37:00 +01:00
|
|
|
|
|
|
|
if not settings.ENTERPRISE:
|
|
|
|
from zilencer.models import get_deployment_by_domain, Deployment
|
|
|
|
else:
|
|
|
|
from mock import Mock
|
|
|
|
get_deployment_by_domain = Mock()
|
|
|
|
Deployment = Mock()
|
|
|
|
|
2013-10-17 16:33:04 +02:00
|
|
|
def get_deployment_or_userprofile(role):
|
|
|
|
return get_user_profile_by_email(role) if "@" in role else get_deployment_by_domain(role)
|
|
|
|
|
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
|
2013-08-06 22:21:12 +02:00
|
|
|
# response will be provided later by calling handler.zulip_finish(),
|
2013-03-15 17:28:03 +01:00
|
|
|
# or has already been provided this way. We use this for longpolling
|
|
|
|
# mode.
|
2012-11-28 06:16:28 +01:00
|
|
|
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-03-26 20:29:47 +01:00
|
|
|
def update_user_activity(request, user_profile):
|
2013-03-25 20:37:00 +01:00
|
|
|
# update_active_status also pushes to rabbitmq, and it seems
|
|
|
|
# redundant to log that here as well.
|
|
|
|
if request.META["PATH_INFO"] == '/json/update_active_status':
|
|
|
|
return
|
2013-10-03 19:48:03 +02:00
|
|
|
|
|
|
|
if hasattr(request, '_query'):
|
|
|
|
query = request._query
|
|
|
|
else:
|
|
|
|
query = request.META['PATH_INFO']
|
|
|
|
|
|
|
|
event={'query': query,
|
2013-03-25 20:37:00 +01:00
|
|
|
'user_profile_id': user_profile.id,
|
|
|
|
'time': datetime_to_timestamp(now()),
|
2013-03-26 20:29:47 +01:00
|
|
|
'client': request.client.name}
|
2013-03-25 20:37:00 +01:00
|
|
|
queue_json_publish("user_activity", event, lambda event: None)
|
2013-01-11 21:16:42 +01:00
|
|
|
|
2013-11-08 02:02:48 +01:00
|
|
|
# Based on django.views.decorators.http.require_http_methods
|
|
|
|
def require_post(func):
|
|
|
|
@wraps(func)
|
|
|
|
def wrapper(request, *args, **kwargs):
|
|
|
|
if (request.method != "POST"
|
|
|
|
and not (request.method == "SOCKET"
|
|
|
|
and request.META['zulip.emulated_method'] == "POST")):
|
|
|
|
if request.method == "SOCKET":
|
|
|
|
err_method = "SOCKET/%s" % (request.META['zulip.emulated_method'],)
|
|
|
|
else:
|
|
|
|
err_method = request.method
|
|
|
|
logging.warning('Method Not Allowed (%s): %s', err_method, request.path,
|
|
|
|
extra={'status_code': 405, 'request': request})
|
|
|
|
return HttpResponseNotAllowed(["POST"])
|
|
|
|
return func(request, *args, **kwargs)
|
|
|
|
return wrapper
|
2012-11-06 20:27:55 +01:00
|
|
|
|
2013-12-09 22:12:18 +01:00
|
|
|
def require_realm_admin(func):
|
|
|
|
@wraps(func)
|
|
|
|
def wrapper(request, user_profile, *args, **kwargs):
|
|
|
|
if not user_profile.has_perm('administer', user_profile.realm):
|
|
|
|
raise JsonableError("Must be a realm administrator")
|
|
|
|
return func(request, user_profile, *args, **kwargs)
|
|
|
|
return wrapper
|
|
|
|
|
2013-06-27 20:21:21 +02:00
|
|
|
default_clients = {}
|
|
|
|
|
|
|
|
def process_client(request, user_profile, default):
|
|
|
|
if 'client' in request.REQUEST:
|
2013-03-21 19:21:46 +01:00
|
|
|
request.client = get_client(request.REQUEST['client'])
|
2013-06-27 20:21:21 +02:00
|
|
|
else:
|
|
|
|
if default not in default_clients:
|
|
|
|
default_clients[default] = get_client(default)
|
|
|
|
request.client = default_clients[default]
|
2013-03-21 19:21:46 +01:00
|
|
|
|
|
|
|
update_user_activity(request, user_profile)
|
|
|
|
|
2013-10-17 16:33:04 +02:00
|
|
|
def validate_api_key(role, api_key):
|
2013-08-21 00:36:45 +02:00
|
|
|
# Remove whitespace to protect users from trivial errors.
|
2013-10-17 16:33:04 +02:00
|
|
|
role, api_key = role.strip(), api_key.strip()
|
2013-08-21 00:36:45 +02:00
|
|
|
|
2013-03-21 19:21:46 +01:00
|
|
|
try:
|
2013-10-17 16:33:04 +02:00
|
|
|
profile = get_deployment_or_userprofile(role)
|
2013-03-21 19:21:46 +01:00
|
|
|
except UserProfile.DoesNotExist:
|
2013-10-17 16:33:04 +02:00
|
|
|
raise JsonableError("Invalid user: %s" % (role,))
|
|
|
|
except Deployment.DoesNotExist:
|
|
|
|
raise JsonableError("Invalid deployment: %s" % (role,))
|
2013-08-21 00:36:45 +02:00
|
|
|
|
2013-10-17 16:33:04 +02:00
|
|
|
if api_key != profile.api_key:
|
2013-08-21 00:09:49 +02:00
|
|
|
if len(api_key) != 32:
|
|
|
|
reason = "Incorrect API key length (keys should be 32 characters long)"
|
|
|
|
else:
|
|
|
|
reason = "Invalid API key"
|
2013-10-17 16:33:04 +02:00
|
|
|
raise JsonableError(reason + " for role '%s'" % (role,))
|
|
|
|
if not profile.is_active:
|
|
|
|
raise JsonableError("Account not active")
|
|
|
|
return profile
|
2013-03-21 19:21:46 +01:00
|
|
|
|
2013-10-03 01:12:57 +02:00
|
|
|
# Use this for webhook views that don't get an email passed in.
|
|
|
|
def api_key_only_webhook_view(view_func):
|
|
|
|
@csrf_exempt
|
|
|
|
@has_request_variables
|
|
|
|
@wraps(view_func)
|
|
|
|
def _wrapped_view_func(request, api_key=REQ,
|
|
|
|
*args, **kwargs):
|
|
|
|
|
|
|
|
try:
|
|
|
|
user_profile = UserProfile.objects.get(api_key=api_key, is_active=True)
|
|
|
|
except UserProfile.DoesNotExist:
|
2013-10-03 20:38:37 +02:00
|
|
|
raise JsonableError("Invalid API key")
|
2013-10-03 01:12:57 +02:00
|
|
|
|
|
|
|
request.user = user_profile
|
|
|
|
request._email = user_profile.email
|
|
|
|
process_client(request, user_profile, "API")
|
|
|
|
rate_limit_user(request, user_profile, domain='all')
|
|
|
|
return view_func(request, user_profile, *args, **kwargs)
|
|
|
|
return _wrapped_view_func
|
|
|
|
|
2013-10-22 15:39:39 +02:00
|
|
|
def zulip_internal(view_func):
|
|
|
|
@login_required(login_url = settings.HOME_NOT_LOGGED_IN)
|
2013-11-01 18:43:38 +01:00
|
|
|
@wraps(view_func)
|
2013-10-22 15:39:39 +02:00
|
|
|
def _wrapped_view_func(request, *args, **kwargs):
|
2013-11-01 18:43:38 +01:00
|
|
|
request._query = view_func.__name__
|
2013-10-22 15:39:39 +02:00
|
|
|
if request.user.realm.domain != 'zulip.com':
|
|
|
|
return HttpResponseRedirect(settings.HOME_NOT_LOGGED_IN)
|
2013-10-22 21:03:34 +02:00
|
|
|
|
|
|
|
request._email = request.user.email
|
|
|
|
process_client(request, request.user, "website")
|
2013-10-22 15:39:39 +02:00
|
|
|
return view_func(request, *args, **kwargs)
|
|
|
|
return _wrapped_view_func
|
2013-10-03 01:12:57 +02:00
|
|
|
|
2013-12-11 20:50:49 +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. It is deprecated in favor on the REST API
|
|
|
|
# versions.
|
2012-11-06 20:27:55 +01:00
|
|
|
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)
|
2013-12-13 20:37:15 +01:00
|
|
|
def _wrapped_view_func(request, email=REQ, api_key=REQ('api_key', default=None),
|
|
|
|
api_key_legacy=REQ('api-key', default=None),
|
2012-11-14 19:45:13 +01:00
|
|
|
*args, **kwargs):
|
2013-12-13 20:37:15 +01:00
|
|
|
if not api_key and not api_key_legacy:
|
|
|
|
raise RequestVariableMissingError("api_key")
|
|
|
|
elif not api_key:
|
|
|
|
api_key = api_key_legacy
|
2013-03-21 19:21:46 +01:00
|
|
|
user_profile = validate_api_key(email, api_key)
|
2013-05-14 16:40:24 +02:00
|
|
|
request.user = user_profile
|
|
|
|
request._email = user_profile.email
|
2013-06-27 20:21:21 +02:00
|
|
|
process_client(request, user_profile, "API")
|
2013-05-29 23:58:07 +02:00
|
|
|
# Apply rate limiting
|
|
|
|
limited_func = rate_limit()(view_func)
|
|
|
|
return limited_func(request, user_profile, *args, **kwargs)
|
2012-11-06 20:27:55 +01:00
|
|
|
return _wrapped_view_func
|
|
|
|
|
2013-08-29 20:47:04 +02:00
|
|
|
# A more REST-y authentication decorator, using, in particular, HTTP Basic
|
|
|
|
# authentication.
|
2013-03-21 20:15:27 +01:00
|
|
|
def authenticated_rest_api_view(view_func):
|
2013-08-16 00:41:35 +02:00
|
|
|
@csrf_exempt
|
2013-03-21 20:15:27 +01:00
|
|
|
@wraps(view_func)
|
|
|
|
def _wrapped_view_func(request, *args, **kwargs):
|
|
|
|
# First try block attempts to get the credentials we need to do authentication
|
|
|
|
try:
|
|
|
|
# Grab the base64-encoded authentication string, decode it, and split it into
|
|
|
|
# the email and API key
|
|
|
|
auth_type, encoded_value = request.META['HTTP_AUTHORIZATION'].split()
|
|
|
|
# case insensitive per RFC 1945
|
|
|
|
if auth_type.lower() != "basic":
|
|
|
|
return json_error("Only Basic authentication is supported.")
|
2013-10-17 16:33:04 +02:00
|
|
|
role, api_key = base64.b64decode(encoded_value).split(":")
|
2013-03-21 20:15:27 +01:00
|
|
|
except ValueError:
|
|
|
|
return json_error("Invalid authorization header for basic auth")
|
|
|
|
except KeyError:
|
2013-07-30 23:20:16 +02:00
|
|
|
return json_unauthorized("Missing authorization header for basic auth")
|
2013-03-21 20:15:27 +01:00
|
|
|
|
|
|
|
# Now we try to do authentication or die
|
|
|
|
try:
|
2013-10-17 16:33:04 +02:00
|
|
|
# Could be a UserProfile or a Deployment
|
|
|
|
profile = validate_api_key(role, api_key)
|
2013-03-21 20:15:27 +01:00
|
|
|
except JsonableError, e:
|
2013-07-30 23:20:16 +02:00
|
|
|
return json_unauthorized(e.error)
|
2013-10-17 16:33:04 +02:00
|
|
|
request.user = profile
|
|
|
|
process_client(request, profile, "API")
|
|
|
|
if isinstance(profile, UserProfile):
|
|
|
|
request._email = profile.email
|
|
|
|
else:
|
|
|
|
request._email = "deployment:" + role
|
|
|
|
profile.rate_limits = ""
|
2013-05-29 23:58:07 +02:00
|
|
|
# Apply rate limiting
|
2013-10-17 16:33:04 +02:00
|
|
|
return rate_limit()(view_func)(request, profile, *args, **kwargs)
|
2013-03-21 20:15:27 +01:00
|
|
|
return _wrapped_view_func
|
|
|
|
|
2013-04-03 21:44:12 +02:00
|
|
|
def process_as_post(view_func):
|
2013-03-21 20:18:44 +01:00
|
|
|
@wraps(view_func)
|
|
|
|
def _wrapped_view_func(request, *args, **kwargs):
|
|
|
|
# Adapted from django/http/__init__.py.
|
|
|
|
# So by default Django doesn't populate request.POST for anything besides
|
2013-04-03 21:44:12 +02:00
|
|
|
# POST requests. We want this dict populated for PATCH/PUT, so we have to
|
2013-03-21 20:18:44 +01:00
|
|
|
# do it ourselves.
|
|
|
|
#
|
|
|
|
# This will not be required in the future, a bug will be filed against
|
|
|
|
# Django upstream.
|
2013-04-03 22:01:58 +02:00
|
|
|
|
|
|
|
if not request.POST:
|
|
|
|
# Only take action if POST is empty.
|
|
|
|
if request.META.get('CONTENT_TYPE', '').startswith('multipart'):
|
2013-08-01 19:33:30 +02:00
|
|
|
# Note that request._files is just the private attribute that backs the
|
|
|
|
# FILES property, so we are essentially setting request.FILES here. (In
|
|
|
|
# Django 1.5 FILES was still a read-only property.)
|
|
|
|
request.POST, request._files = MultiPartParser(request.META, StringIO(request.body),
|
|
|
|
request.upload_handlers, request.encoding).parse()
|
2013-04-03 22:01:58 +02:00
|
|
|
else:
|
|
|
|
request.POST = QueryDict(request.body, encoding=request.encoding)
|
2013-03-21 20:18:44 +01:00
|
|
|
|
|
|
|
return view_func(request, *args, **kwargs)
|
|
|
|
|
|
|
|
return _wrapped_view_func
|
|
|
|
|
2013-06-27 20:21:21 +02:00
|
|
|
def authenticate_log_and_execute_json(request, view_func, *args, **kwargs):
|
2012-12-02 20:51:51 +01:00
|
|
|
if not request.user.is_authenticated():
|
|
|
|
return json_error("Not logged in", status=401)
|
2013-03-29 17:39:53 +01:00
|
|
|
user_profile = request.user
|
2013-06-27 20:21:21 +02:00
|
|
|
process_client(request, user_profile, "website")
|
2013-03-28 20:43:34 +01:00
|
|
|
request._email = user_profile.email
|
2012-12-02 20:51:51 +01:00
|
|
|
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,
|
|
|
|
*args, **kwargs):
|
2013-06-27 20:21:21 +02:00
|
|
|
return authenticate_log_and_execute_json(request, view_func, *args, **kwargs)
|
2012-12-02 20:51:51 +01:00
|
|
|
return _wrapped_view_func
|
|
|
|
|
|
|
|
def authenticated_json_view(view_func):
|
|
|
|
@wraps(view_func)
|
|
|
|
def _wrapped_view_func(request,
|
|
|
|
*args, **kwargs):
|
2013-06-27 20:21:21 +02:00
|
|
|
return authenticate_log_and_execute_json(request, 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'
|
2013-02-11 23:15:34 +01:00
|
|
|
request._email = "internal"
|
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
|
2013-05-08 20:16:16 +02:00
|
|
|
class REQ(object):
|
2012-11-01 23:21:12 +01:00
|
|
|
# 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
|
2013-05-08 20:16:16 +02:00
|
|
|
# instance of the REQ 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
|
2013-03-26 18:04:51 +01:00
|
|
|
if default_param_values is None:
|
|
|
|
default_param_values = []
|
2012-11-01 23:21:12 +01:00
|
|
|
|
|
|
|
post_params = []
|
|
|
|
|
|
|
|
for (name, value) in zip(default_param_names, default_param_values):
|
2013-05-08 20:16:16 +02:00
|
|
|
if isinstance(value, REQ):
|
2012-11-01 23:21:12 +01:00
|
|
|
value.func_var_name = name
|
|
|
|
if value.post_var_name is None:
|
|
|
|
value.post_var_name = name
|
|
|
|
post_params.append(value)
|
2013-05-08 20:16:16 +02:00
|
|
|
elif value == REQ:
|
|
|
|
# If the function definition does not actually instantiate
|
|
|
|
# a REQ object but instead uses the REQ class itself as a
|
|
|
|
# value, we instantiate it as a convenience
|
2013-03-22 15:57:31 +01:00
|
|
|
post_var = value(name)
|
2012-11-01 23:21:12 +01:00
|
|
|
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:
|
2013-05-08 20:16:16 +02:00
|
|
|
val = request.REQUEST[param.post_var_name]
|
2012-11-01 23:21:12 +01:00
|
|
|
except KeyError:
|
2013-05-08 20:16:16 +02:00
|
|
|
if param.default is REQ.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-06-18 23:55:55 +02:00
|
|
|
data = ujson.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)
|
2013-04-16 22:52:32 +02:00
|
|
|
|
|
|
|
def statsd_increment(counter, val=1):
|
|
|
|
"""Increments a statsd counter on completion of the
|
|
|
|
decorated function.
|
|
|
|
|
|
|
|
Pass the name of the counter to this decorator-returning function."""
|
|
|
|
def wrapper(func):
|
|
|
|
@wraps(func)
|
|
|
|
def wrapped_func(*args, **kwargs):
|
2013-05-29 23:58:07 +02:00
|
|
|
ret = func(*args, **kwargs)
|
2013-04-16 22:52:32 +02:00
|
|
|
statsd.incr(counter, val)
|
2013-05-29 23:58:07 +02:00
|
|
|
return ret
|
|
|
|
return wrapped_func
|
|
|
|
return wrapper
|
|
|
|
|
2013-06-06 20:08:02 +02:00
|
|
|
def rate_limit_user(request, user, domain):
|
|
|
|
"""Returns whether or not a user was rate limited. Will raise a RateLimited exception
|
|
|
|
if the user has been rate limited, otherwise returns and modifies request to contain
|
|
|
|
the rate limit information"""
|
|
|
|
|
|
|
|
ratelimited, time = is_ratelimited(user, domain)
|
|
|
|
request._ratelimit_applied_limits = True
|
|
|
|
request._ratelimit_secs_to_freedom = time
|
|
|
|
request._ratelimit_over_limit = ratelimited
|
|
|
|
# Abort this request if the user is over her rate limits
|
|
|
|
if ratelimited:
|
2013-10-17 16:33:04 +02:00
|
|
|
statsd.incr("ratelimiter.limited.%s.%s" % (type(user), user.id))
|
2013-06-06 20:08:02 +02:00
|
|
|
raise RateLimited()
|
|
|
|
|
|
|
|
incr_ratelimit(user, domain)
|
|
|
|
calls_remaining, time_reset = api_calls_left(user, domain)
|
|
|
|
|
|
|
|
request._ratelimit_remaining = calls_remaining
|
|
|
|
request._ratelimit_secs_to_freedom = time_reset
|
|
|
|
|
2013-05-29 23:58:07 +02:00
|
|
|
def rate_limit(domain='all'):
|
|
|
|
"""Rate-limits a view. Takes an optional 'domain' param if you wish to rate limit different
|
|
|
|
types of API calls independently.
|
|
|
|
|
|
|
|
Returns a decorator"""
|
|
|
|
def wrapper(func):
|
|
|
|
@wraps(func)
|
|
|
|
def wrapped_func(request, *args, **kwargs):
|
|
|
|
# Don't rate limit requests from Django that come from our own servers,
|
|
|
|
# and don't rate-limit dev instances
|
|
|
|
no_limits = False
|
|
|
|
if request.client and request.client.name.lower() == 'internal' and \
|
|
|
|
(request.META['REMOTE_ADDR'] in ['::1', '127.0.0.1'] or settings.DEBUG):
|
|
|
|
no_limits = True
|
|
|
|
|
|
|
|
if no_limits:
|
|
|
|
return func(request, *args, **kwargs)
|
|
|
|
|
|
|
|
try:
|
|
|
|
user = request.user
|
|
|
|
except:
|
|
|
|
user = None
|
|
|
|
|
|
|
|
# Rate-limiting data is stored in redis
|
|
|
|
# We also only support rate-limiting authenticated
|
|
|
|
# views right now.
|
|
|
|
# TODO(leo) - implement per-IP non-authed rate limiting
|
|
|
|
if not settings.RATE_LIMITING or not user:
|
|
|
|
if not user:
|
|
|
|
logging.error("Requested rate-limiting on %s but user is not authenticated!" % \
|
|
|
|
func.__name__)
|
|
|
|
return func(request, *args, **kwargs)
|
|
|
|
|
2013-06-06 20:08:02 +02:00
|
|
|
rate_limit_user(request, user, domain)
|
2013-05-29 23:58:07 +02:00
|
|
|
|
|
|
|
return func(request, *args, **kwargs)
|
2013-04-16 22:52:32 +02:00
|
|
|
return wrapped_func
|
|
|
|
return wrapper
|
2013-07-02 17:30:04 +02:00
|
|
|
|
|
|
|
def profiled(func):
|
|
|
|
"""
|
|
|
|
This decorator should obviously be used only in a dev environment.
|
|
|
|
It works best when surrounding a function that you expect to be
|
2013-07-29 23:03:31 +02:00
|
|
|
called once. One strategy is to write a test case in zerver/tests.py
|
2013-07-02 17:30:04 +02:00
|
|
|
and wrap the test case with the profiled decorator.
|
|
|
|
|
|
|
|
You can run a single test case like this:
|
|
|
|
|
2013-07-29 23:03:31 +02:00
|
|
|
# edit zerver/tests.py and place @profiled above the test case below
|
|
|
|
./tools/test-backend zerver.RateLimitTests.test_ratelimit_decrease
|
2013-07-02 17:30:04 +02:00
|
|
|
|
|
|
|
Then view the results like this:
|
|
|
|
|
|
|
|
./tools/show-profile-results.py test_ratelimit_decrease.profile
|
|
|
|
|
|
|
|
"""
|
|
|
|
@wraps(func)
|
|
|
|
def wrapped_func(*args, **kwargs):
|
|
|
|
fn = func.__name__ + ".profile"
|
|
|
|
prof = cProfile.Profile()
|
|
|
|
retval = prof.runcall(func, *args, **kwargs)
|
|
|
|
prof.dump_stats(fn)
|
|
|
|
return retval
|
|
|
|
return wrapped_func
|
2013-10-07 17:35:22 +02:00
|
|
|
|
|
|
|
def uses_mandrill(func):
|
|
|
|
"""
|
|
|
|
This decorator takes a function with keyword argument "mail_client" and
|
|
|
|
fills it in with the mail_client for the Mandrill account.
|
|
|
|
"""
|
|
|
|
@wraps(func)
|
|
|
|
def wrapped_func(*args, **kwargs):
|
|
|
|
kwargs['mail_client'] = get_mandrill_client()
|
|
|
|
return func(*args, **kwargs)
|
|
|
|
return wrapped_func
|
|
|
|
|