示例#1
0
 def test_various_statuses(self):
     created = HttpCreated(location='http://example.com/thingy/1/')
     self.assertEqual(created.status_code, 201)
     self.assertEqual(created['Location'], 'http://example.com/thingy/1/')
     # Regression.
     created_2 = HttpCreated()
     self.assertEqual(created_2.status_code, 201)
     self.assertEqual(created_2['Location'], '')
     accepted = HttpAccepted()
     self.assertEqual(accepted.status_code, 202)
     no_content = HttpNoContent()
     self.assertEqual(no_content.status_code, 204)
     see_other = HttpSeeOther()
     self.assertEqual(see_other.status_code, 303)
     not_modified = HttpNotModified()
     self.assertEqual(not_modified.status_code, 304)
     bad_request = HttpBadRequest()
     self.assertEqual(bad_request.status_code, 400)
     unauthorized = HttpUnauthorized()
     self.assertEqual(unauthorized.status_code, 401)
     not_found = HttpNotFound()
     self.assertEqual(not_found.status_code, 404)
     not_allowed = HttpMethodNotAllowed()
     self.assertEqual(not_allowed.status_code, 405)
     conflict = HttpConflict()
     self.assertEqual(conflict.status_code, 409)
     gone = HttpGone()
     self.assertEqual(gone.status_code, 410)
     toomanyrequests = HttpTooManyRequests()
     self.assertEqual(toomanyrequests.status_code, 429)
     not_implemented = HttpNotImplemented()
     self.assertEqual(not_implemented.status_code, 501)
示例#2
0
    def send_sms(self, device, token):
        if rate_limit_two_factor_setup(device):
            return HttpTooManyRequests()

        message = _('Your authentication token is %s') % token
        self.client.api.account.messages.create(to=device.number.as_e164,
                                                from_=self.from_number,
                                                body=message)
示例#3
0
def restore(request, domain, app_id=None):
    """
    We override restore because we have to supply our own
    user model (and have the domain in the url)
    """
    if rate_limit_restore(domain):
        return HttpTooManyRequests()

    response, timing_context = get_restore_response(
        domain, request.couch_user, app_id, **get_restore_params(request))
    return response
示例#4
0
    def throttle_check(self, request):
        """Override throttle check to throttle differently on GET and POST.
       """
        identifier = self._meta.authentication.get_identifier(request)

        if request.method == 'POST':
            if self._meta.post_throttle.should_be_throttled(identifier):
                raise ImmediateHttpResponse(response=HttpTooManyRequests())

        else:
            return super(CollMapResource, self).throttle_check(request)
示例#5
0
    def make_call(self, device, token):
        if rate_limit_two_factor_setup(device):
            return HttpTooManyRequests()

        locale = translation.get_language()
        validate_voice_locale(locale)

        url = reverse('two_factor_twilio:call_app', kwargs={'token': token})
        url = '%s?%s' % (url, urlencode({'locale': locale}))
        uri = 'https://%s%s' % (Site.objects.get_current().domain, url)
        self.client.api.account.calls.create(to=device.number.as_e164, from_=self.from_number,
                                 url=uri, method='GET', if_machine='Hangup', timeout=15)
示例#6
0
    def send_sms(self, device, token):
        if rate_limit_two_factor_setup(device):
            return HttpTooManyRequests()

        message = _('Your authentication token is %s') % token
        try:
            self.client.api.account.messages.create(to=device.number.as_e164,
                                                    from_=self.from_number,
                                                    body=message)
        except TwilioRestException as e:
            request = get_request()
            notify_exception(request, str(e))
            if request:
                messages.error(
                    request,
                    _('''
                    Error received from SMS partner. If you do not receive a token, please retry in a few minutes.
                '''))
示例#7
0
def _process_form(request,
                  domain,
                  app_id,
                  user_id,
                  authenticated,
                  auth_cls=AuthContext):

    if rate_limit_submission(domain):
        return HttpTooManyRequests()

    metric_tags = {'backend': 'sql', 'domain': domain}

    try:
        instance, attachments = couchforms.get_instance_and_attachment(request)
    except MultimediaBug:
        try:
            instance = request.FILES[MAGIC_PROPERTY].read()
            xform = convert_xform_to_json(instance)
            meta = xform.get("meta", {})
        except Exception:
            meta = {}

        metrics_counter('commcare.corrupt_multimedia_submissions',
                        tags={
                            'domain': domain,
                            'authenticated': authenticated
                        })
        return _submission_error(
            request,
            "Received a submission with POST.keys()",
            metric_tags,
            domain,
            app_id,
            user_id,
            authenticated,
            meta,
        )
    # the order of these exceptions is relevant
    except UnprocessableFormSubmission as e:
        return openrosa_response.OpenRosaResponse(
            message=e.message,
            nature=openrosa_response.ResponseNature.PROCESSING_FAILURE,
            status=e.status_code,
        ).response()
    except BadSubmissionRequest as e:
        response = HttpResponse(e.message, status=e.status_code)
        _record_metrics(metric_tags, 'known_failures', response)
        return response

    if should_ignore_submission(request):
        # silently ignore submission if it meets ignore-criteria
        response = openrosa_response.SUBMISSION_IGNORED_RESPONSE
        _record_metrics(metric_tags, 'ignored', response)
        return response

    if toggles.FORM_SUBMISSION_BLACKLIST.enabled(domain):
        response = openrosa_response.BLACKLISTED_RESPONSE
        _record_metrics(metric_tags, 'blacklisted', response)
        return response

    with TimingContext() as timer:
        app_id, build_id = get_app_and_build_ids(domain, app_id)
        submission_post = SubmissionPost(
            instance=instance,
            attachments=attachments,
            domain=domain,
            app_id=app_id,
            build_id=build_id,
            auth_context=auth_cls(
                domain=domain,
                user_id=user_id,
                authenticated=authenticated,
            ),
            location=couchforms.get_location(request),
            received_on=couchforms.get_received_on(request),
            date_header=couchforms.get_date_header(request),
            path=couchforms.get_path(request),
            submit_ip=couchforms.get_submit_ip(request),
            last_sync_token=couchforms.get_last_sync_token(request),
            openrosa_headers=couchforms.get_openrosa_headers(request),
            force_logs=request.GET.get('force_logs', 'false') == 'true',
            timing_context=timer)

        try:
            result = submission_post.run()
        except XFormLockError as err:
            logging.warning('Unable to get lock for form %s', err)
            metrics_counter('commcare.xformlocked.count',
                            tags={
                                'domain': domain,
                                'authenticated': authenticated
                            })
            return _submission_error(
                request,
                "XFormLockError: %s" % err,
                metric_tags,
                domain,
                app_id,
                user_id,
                authenticated,
                status=423,
                notify=False,
            )

    response = result.response
    response.request_timer = timer  # logged as Sentry breadcrumbs in LogLongRequestMiddleware

    _record_metrics(metric_tags, result.submission_type, result.response,
                    timer, result.xform)

    return response
示例#8
0
def _process_form(request,
                  domain,
                  app_id,
                  user_id,
                  authenticated,
                  auth_cls=AuthContext):

    if rate_limit_submission(domain):
        return HttpTooManyRequests()

    metric_tags = {
        'backend': 'sql' if should_use_sql_backend(domain) else 'couch',
        'domain': domain
    }

    try:
        instance, attachments = couchforms.get_instance_and_attachment(request)
    except MultimediaBug:
        try:
            instance = request.FILES[MAGIC_PROPERTY].read()
            xform = convert_xform_to_json(instance)
            meta = xform.get("meta", {})
        except:
            meta = {}

        metrics_counter('commcare.corrupt_multimedia_submissions',
                        tags={
                            'domain': domain,
                            'authenticated': authenticated
                        })
        return _submission_error(
            request,
            "Received a submission with POST.keys()",
            metric_tags,
            domain,
            app_id,
            user_id,
            authenticated,
            meta,
        )

    if isinstance(instance, BadRequest):
        response = HttpResponseBadRequest(instance.message)
        _record_metrics(metric_tags, 'known_failures', response)
        return response

    if should_ignore_submission(request):
        # silently ignore submission if it meets ignore-criteria
        response = openrosa_response.SUBMISSION_IGNORED_RESPONSE
        _record_metrics(metric_tags, 'ignored', response)
        return response

    if toggles.FORM_SUBMISSION_BLACKLIST.enabled(domain):
        response = openrosa_response.BLACKLISTED_RESPONSE
        _record_metrics(metric_tags, 'blacklisted', response)
        return response

    with TimingContext() as timer:
        app_id, build_id = get_app_and_build_ids(domain, app_id)
        submission_post = SubmissionPost(
            instance=instance,
            attachments=attachments,
            domain=domain,
            app_id=app_id,
            build_id=build_id,
            auth_context=auth_cls(
                domain=domain,
                user_id=user_id,
                authenticated=authenticated,
            ),
            location=couchforms.get_location(request),
            received_on=couchforms.get_received_on(request),
            date_header=couchforms.get_date_header(request),
            path=couchforms.get_path(request),
            submit_ip=couchforms.get_submit_ip(request),
            last_sync_token=couchforms.get_last_sync_token(request),
            openrosa_headers=couchforms.get_openrosa_headers(request),
            force_logs=request.GET.get('force_logs', 'false') == 'true',
        )

        try:
            result = submission_post.run()
        except XFormLockError as err:
            metrics_counter('commcare.xformlocked.count',
                            tags={
                                'domain': domain,
                                'authenticated': authenticated
                            })
            return _submission_error(
                request,
                "XFormLockError: %s" % err,
                metric_tags,
                domain,
                app_id,
                user_id,
                authenticated,
                status=423,
                notify=False,
            )

    response = result.response
    _record_metrics(metric_tags, result.submission_type, result.response,
                    timer, result.xform)

    return response