Ejemplo n.º 1
0
    def test_sample_inactive_all_sites_override(self):
        name = 'mysample'
        Sample.objects.create(name=name, percent='0.0', site=self.site1)
        self.assertFalse(waffle.sample_is_active(get(), name))

        with self.settings(SITE_ID=2):
            self.assertFalse(waffle.sample_is_active(get(), name))
Ejemplo n.º 2
0
    def test_sample_site_default(self):
        name = 'sample'
        sample = Sample.objects.create(name=name, percent='100.0') # no site given

        self.assertTrue(waffle.sample_is_active(name))

        with self.settings(SITE_ID=2):
            self.assertTrue(waffle.sample_is_active(name))
Ejemplo n.º 3
0
    def test_sample_site_default(self):
        name = "sample"
        sample = Sample.objects.create(name=name, percent="100.0")  # no site given

        self.assertTrue(waffle.sample_is_active(get(), name))

        with self.settings(SITE_ID=2):
            self.assertTrue(waffle.sample_is_active(get(), name))
Ejemplo n.º 4
0
    def test_sample_by_site(self):
        name = 'sample'
        sample1 = Sample.objects.create(name=name, percent='100.0', site=self.site1)
        sample2 = Sample.objects.create(name=name, percent='0.0', site=self.site2)

        self.assertTrue(waffle.sample_is_active(name))

        with self.settings(SITE_ID=2):
            self.assertFalse(waffle.sample_is_active(name))
Ejemplo n.º 5
0
    def test_sample_by_site(self):
        name = "sample"
        sample1 = Sample.objects.create(name=name, percent="100.0", site=self.site1)
        sample2 = Sample.objects.create(name=name, percent="0.0", site=self.site2)

        self.assertTrue(waffle.sample_is_active(get(), name))

        with self.settings(SITE_ID=2):
            self.assertFalse(waffle.sample_is_active(get(), name))
Ejemplo n.º 6
0
    def test_pluggable_sample_model(self):
        sample_model = waffle.get_waffle_model('SAMPLE_MODEL')
        self.assertEqual(CustomSample, sample_model)

        sample_model.objects.create(name='test_sample_off', percent=0)
        sample_model.objects.create(name='test_sample_on', percent=100)

        assert not waffle.sample_is_active('test_sample_off')
        assert waffle.sample_is_active('test_sample_on')
Ejemplo n.º 7
0
    def test_sample_did_not_exist(self):
        assert not Sample.objects.filter(name='foo').exists()

        with override_sample('foo', active=True):
            assert waffle.sample_is_active('foo')

        with override_sample('foo', active=False):
            assert not waffle.sample_is_active('foo')

        assert not Sample.objects.filter(name='foo').exists()
Ejemplo n.º 8
0
    def test_sample_existed_and_was_50(self):
        Sample.objects.create(name="foo", percent="50.0")

        with override_sample("foo", active=True):
            assert waffle.sample_is_active(req(), "foo")

        with override_sample("foo", active=False):
            assert not waffle.sample_is_active("foo")

        self.assertEquals(Decimal("50.0"), Sample.objects.get(name="foo").percent)
Ejemplo n.º 9
0
    def test_sample_did_not_exist(self):
        assert not Sample.objects.filter(name="foo").exists()

        with override_sample("foo", active=True):
            assert waffle.sample_is_active(req(), "foo")

        with override_sample("foo", active=False):
            assert not waffle.sample_is_active(req(), "foo")

        assert not Sample.objects.filter(name="foo").exists()
Ejemplo n.º 10
0
    def test_cache_is_flushed_by_testutils_even_in_transaction(self):
        Sample.objects.create(name='foo', percent='100.0')

        with transaction.atomic():
            with override_sample('foo', active=True):
                assert waffle.sample_is_active('foo')

            with override_sample('foo', active=False):
                assert not waffle.sample_is_active('foo')

        assert waffle.sample_is_active('foo')
Ejemplo n.º 11
0
    def test_sample_existed_and_was_50(self):
        Sample.objects.create(name='foo', percent='50.0')

        with override_sample('foo', active=True):
            assert waffle.sample_is_active('foo')

        with override_sample('foo', active=False):
            assert not waffle.sample_is_active('foo')

        self.assertEquals(Decimal('50.0'),
                          Sample.objects.get(name='foo').percent)
Ejemplo n.º 12
0
    def test_cache_is_flushed_by_testutils_even_in_transaction(self):
        Sample.objects.create(name='foo', percent='100.0')

        with transaction.atomic():
            with override_sample('foo', active=True):
                assert waffle.sample_is_active('foo')

            with override_sample('foo', active=False):
                assert not waffle.sample_is_active('foo')

        assert waffle.sample_is_active('foo')
Ejemplo n.º 13
0
    def test_read_from_write_db(self):
        sample = Sample.objects.create(name='sample', percent='100.0')

        # By default, sample_is_active should hit whatever it configured as the
        # read DB (so values will be stale if replication is lagged).
        assert not waffle.sample_is_active(sample.name)

        with override_settings(WAFFLE_READ_FROM_WRITE_DB=True):
            # Save the sample again to flush the cache.
            sample.save()

            # The next read should now be directed to the write DB, ensuring
            # the cache and DB are in sync.
            assert waffle.sample_is_active(sample.name)
Ejemplo n.º 14
0
    def test_read_from_write_db(self):
        sample = Sample.objects.create(name='sample', percent='100.0')

        # By default, sample_is_active should hit whatever it configured as the
        # read DB (so values will be stale if replication is lagged).
        assert not waffle.sample_is_active(sample.name)

        with override_settings(WAFFLE_READ_FROM_WRITE_DB=True):
            # Save the sample again to flush the cache.
            sample.save()

            # The next read should now be directed to the write DB, ensuring
            # the cache and DB are in sync.
            assert waffle.sample_is_active(sample.name)
Ejemplo n.º 15
0
def _generate_waffle_js(request):
    flags = cache.get(keyfmt(FLAGS_ALL_CACHE_KEY))
    if not flags:
        flags = Flag.objects.values_list("name", flat=True)
        cache.add(keyfmt(FLAGS_ALL_CACHE_KEY), flags)
    flag_values = [(f, flag_is_active(request, f)) for f in flags]

    switches = cache.get(keyfmt(SWITCHES_ALL_CACHE_KEY))
    if not switches:
        switches = Switch.objects.values_list("name", "active")
        cache.add(keyfmt(SWITCHES_ALL_CACHE_KEY), switches)

    samples = cache.get(keyfmt(SAMPLES_ALL_CACHE_KEY))
    if not samples:
        samples = Sample.objects.values_list("name", flat=True)
        cache.add(keyfmt(SAMPLES_ALL_CACHE_KEY), samples)
    sample_values = [(s, sample_is_active(s)) for s in samples]

    flag_default = getattr(settings, "WAFFLE_FLAG_DEFAULT", False)
    switch_default = getattr(settings, "WAFFLE_SWITCH_DEFAULT", False)
    sample_default = getattr(settings, "WAFFLE_SAMPLE_DEFAULT", False)

    return loader.render_to_string(
        "waffle/waffle.js",
        {
            "flags": flag_values,
            "switches": switches,
            "samples": sample_values,
            "flag_default": flag_default,
            "switch_default": switch_default,
            "sample_default": sample_default,
        },
    )
Ejemplo n.º 16
0
def cspreport(request):
    """Accept CSP reports and log them."""
    report = ("blocked-uri", "violated-directive", "original-policy")

    if not waffle.sample_is_active("csp-store-reports"):
        return HttpResponse()

    try:
        v = json.loads(request.body)["csp-report"]
        # If possible, alter the PATH_INFO to contain the request of the page
        # the error occurred on, spec: http://mzl.la/P82R5y
        meta = request.META.copy()
        meta["PATH_INFO"] = v.get("document-uri", meta["PATH_INFO"])
        v = [(k, v[k]) for k in report if k in v]
        log_cef(
            "CSPViolation",
            5,
            meta,
            username=request.user,
            signature="CSPREPORT",
            msg="A client reported a CSP violation",
            cs6=v,
            cs6Label="ContentPolicy",
        )
    except (KeyError, ValueError), e:
        log.debug("Exception in CSP report: %s" % e, exc_info=True)
        return HttpResponseBadRequest()
Ejemplo n.º 17
0
def cspreport(request):
    """Accept CSP reports and log them."""
    report = ('blocked-uri', 'violated-directive', 'original-policy')

    if not waffle.sample_is_active('csp-store-reports'):
        return HttpResponse()

    try:
        v = json.loads(request.body)['csp-report']
        # If possible, alter the PATH_INFO to contain the request of the page
        # the error occurred on, spec: http://mzl.la/P82R5y
        meta = request.META.copy()
        meta['PATH_INFO'] = v.get('document-uri', meta['PATH_INFO'])
        v = [(k, v[k]) for k in report if k in v]
        log_cef('CSP Violation',
                5,
                meta,
                username=request.user,
                signature='CSPREPORT',
                msg='A client reported a CSP violation',
                cs6=v,
                cs6Label='ContentPolicy')
    except (KeyError, ValueError), e:
        log.debug('Exception in CSP report: %s' % e, exc_info=True)
        return HttpResponseBadRequest()
Ejemplo n.º 18
0
def _generate_waffle_js(request):
    flags = cache.get(keyfmt(FLAGS_ALL_CACHE_KEY))
    if not flags:
        flags = Flag.objects.values_list('name', flat=True)
        cache.add(keyfmt(FLAGS_ALL_CACHE_KEY), flags)
    flag_values = [(f, flag_is_active(request, f)) for f in flags]

    switches = cache.get(keyfmt(SWITCHES_ALL_CACHE_KEY))
    if not switches:
        switches = Switch.objects.values_list('name', 'active')
        cache.add(keyfmt(SWITCHES_ALL_CACHE_KEY), switches)

    samples = cache.get(keyfmt(SAMPLES_ALL_CACHE_KEY))
    if not samples:
        samples = Sample.objects.values_list('name', flat=True)
        cache.add(keyfmt(SAMPLES_ALL_CACHE_KEY), samples)
    sample_values = [(s, sample_is_active(s)) for s in samples]

    flag_default = getattr(settings, 'WAFFLE_FLAG_DEFAULT', False)
    switch_default = getattr(settings, 'WAFFLE_SWITCH_DEFAULT', False)
    sample_default = getattr(settings, 'WAFFLE_SAMPLE_DEFAULT', False)

    return loader.render_to_string('waffle/waffle.js',
                              {
                                'flags': flag_values,
                                'switches': switches,
                                'samples': sample_values,
                                'flag_default': flag_default,
                                'switch_default': switch_default,
                                'sample_default': sample_default,
                              })
Ejemplo n.º 19
0
def _generate_waffle_js(request):
    flags = cache.get(keyfmt(get_setting('ALL_FLAGS_CACHE_KEY')))
    if flags is None:
        flags = Flag.objects.values_list('name', flat=True)
        cache.add(keyfmt(get_setting('ALL_FLAGS_CACHE_KEY')), flags)
    flag_values = [(f, flag_is_active(request, f)) for f in flags]

    switches = cache.get(keyfmt(get_setting('ALL_SWITCHES_CACHE_KEY')))
    if switches is None:
        switches = Switch.objects.values_list('name', 'active')
        cache.add(keyfmt(get_setting('ALL_SWITCHES_CACHE_KEY')), switches)

    samples = cache.get(keyfmt(get_setting('ALL_SAMPLES_CACHE_KEY')))
    if samples is None:
        samples = Sample.objects.values_list('name', flat=True)
        cache.add(keyfmt(get_setting('ALL_SAMPLES_CACHE_KEY')), samples)
    sample_values = [(s, sample_is_active(s)) for s in samples]

    return loader.render_to_string(
        'waffle/waffle.js', {
            'flags': flag_values,
            'switches': switches,
            'samples': sample_values,
            'flag_default': get_setting('FLAG_DEFAULT'),
            'switch_default': get_setting('SWITCH_DEFAULT'),
            'sample_default': get_setting('SAMPLE_DEFAULT'),
        })
Ejemplo n.º 20
0
 def export(self, **kwargs):
     """
     Return the exported and transformed content metadata as a dictionary.
     """
     content_metadata_export = {}
     if waffle.sample_is_active(USE_ENTERPRISE_CATALOG):
         content_metadata_items = self.enterprise_catalog_api.get_content_metadata(
             self.enterprise_customer,
             enterprise_catalogs=self.enterprise_configuration.
             customer_catalogs_to_transmit)
         LOGGER.info(
             'Getting metadata for Enterprise [%s], Catalogs [%s] from Enterprise Catalog Service. Results: [%s]',
             self.enterprise_customer.name,
             self.enterprise_configuration.customer_catalogs_to_transmit,
             json.dumps(content_metadata_items))
     else:
         content_metadata_items = self.enterprise_api.get_content_metadata(
             self.enterprise_customer,
             enterprise_catalogs=self.enterprise_configuration.
             customer_catalogs_to_transmit)
     LOGGER.info('Retrieved content metadata for enterprise [%s]',
                 self.enterprise_customer.name)
     for item in content_metadata_items:
         transformed = self._transform_item(item)
         LOGGER.debug(
             'Exporting content metadata item with plugin configuration [%s]: [%s]',
             self.enterprise_configuration,
             json.dumps(transformed, indent=4),
         )
         content_metadata_item_export = ContentMetadataItemExport(
             item, transformed)
         content_metadata_export[content_metadata_item_export.
                                 content_id] = content_metadata_item_export
     return OrderedDict(sorted(content_metadata_export.items()))
Ejemplo n.º 21
0
def _generate_waffle_js(request):
    flags = cache.get(keyfmt(get_setting('ALL_FLAGS_CACHE_KEY')))
    if flags is None:
        flags = Flag.objects.values_list('name', flat=True)
        cache.add(keyfmt(get_setting('ALL_FLAGS_CACHE_KEY')), flags)
    flag_values = [(f, flag_is_active(request, f)) for f in flags]

    switches = cache.get(keyfmt(get_setting('ALL_SWITCHES_CACHE_KEY')))
    if switches is None:
        switches = Switch.objects.values_list('name', 'active')
        cache.add(keyfmt(get_setting('ALL_SWITCHES_CACHE_KEY')), switches)

    samples = cache.get(keyfmt(get_setting('ALL_SAMPLES_CACHE_KEY')))
    if samples is None:
        samples = Sample.objects.values_list('name', flat=True)
        cache.add(keyfmt(get_setting('ALL_SAMPLES_CACHE_KEY')), samples)
    sample_values = [(s, sample_is_active(s)) for s in samples]

    return loader.render_to_string('waffle/waffle.js', {
        'flags': flag_values,
        'switches': switches,
        'samples': sample_values,
        'flag_default': get_setting('FLAG_DEFAULT'),
        'switch_default': get_setting('SWITCH_DEFAULT'),
        'sample_default': get_setting('SAMPLE_DEFAULT'),
    })
Ejemplo n.º 22
0
def cspreport(request):
    """Accept CSP reports and log them."""
    report = ("blocked-uri", "violated-directive", "original-policy")

    if not waffle.sample_is_active("csp-store-reports"):
        return HttpResponse()

    try:
        v = json.loads(request.raw_post_data)["csp-report"]
        # CEF module wants a dictionary of environ, we want request
        # to be the page with error on it, that's contained in the csp-report
        # so we need to modify the meta before we pass in to the logger
        meta = request.META.copy()
        method, url = v["request"].split(" ", 1)
        meta.update({"REQUEST_METHOD": method, "PATH_INFO": url})
        v = [(k, v[k]) for k in report if k in v]
        log_cef(
            "CSP Violation",
            5,
            meta,
            username=request.user,
            signature="CSPREPORT",
            msg="A client reported a CSP violation",
            cs7=v,
            cs7Label="ContentPolicy",
        )
    except Exception, e:
        log.debug("Exception in CSP report: %s" % e, exc_info=True)
        return HttpResponseBadRequest()
Ejemplo n.º 23
0
Archivo: views.py Proyecto: vdt/zamboni
def cspreport(request):
    """Accept CSP reports and log them."""
    report = ('blocked-uri', 'violated-directive', 'original-policy')

    if not waffle.sample_is_active('csp-store-reports'):
        return HttpResponse()

    try:
        v = json.loads(request.raw_post_data)['csp-report']
        # CEF module wants a dictionary of environ, we want request
        # to be the page with error on it, that's contained in the csp-report
        # so we need to modify the meta before we pass in to the logger
        meta = request.META.copy()
        method, url = v['request'].split(' ', 1)
        meta.update({'REQUEST_METHOD': method, 'PATH_INFO': url})
        v = [(k, v[k]) for k in report if k in v]
        log_cef('CSP Violation',
                5,
                meta,
                username=request.user,
                signature='CSPREPORT',
                msg='A client reported a CSP violation',
                cs7=v,
                cs7Label='ContentPolicy')
    except Exception, e:
        log.debug('Exception in CSP report: %s' % e, exc_info=True)
        return HttpResponseBadRequest()
Ejemplo n.º 24
0
def _generate_waffle_js(request):
    flags = cache.get(keyfmt(FLAGS_ALL_CACHE_KEY))
    if not flags:
        flags = Flag.objects.values_list('name', flat=True)
        cache.add(keyfmt(FLAGS_ALL_CACHE_KEY), flags)
    flag_values = [(f, flag_is_active(request, f)) for f in flags]

    switches = cache.get(keyfmt(SWITCHES_ALL_CACHE_KEY))
    if not switches:
        switches = Switch.objects.values_list('name', 'active')
        cache.add(keyfmt(SWITCHES_ALL_CACHE_KEY), switches)

    samples = cache.get(keyfmt(SAMPLES_ALL_CACHE_KEY))
    if not samples:
        samples = Sample.objects.values_list('name', flat=True)
        cache.add(keyfmt(SAMPLES_ALL_CACHE_KEY), samples)
    sample_values = [(s, sample_is_active(s)) for s in samples]

    flag_default = getattr(settings, 'WAFFLE_FLAG_DEFAULT', False)
    switch_default = getattr(settings, 'WAFFLE_SWITCH_DEFAULT', False)
    sample_default = getattr(settings, 'WAFFLE_SAMPLE_DEFAULT', False)

    return loader.render_to_string(
        'waffle/waffle.js', {
            'flags': flag_values,
            'switches': switches,
            'samples': sample_values,
            'flag_default': flag_default,
            'switch_default': switch_default,
            'sample_default': sample_default,
        })
Ejemplo n.º 25
0
def wafflejs(request):
    flags = cache.get(keyfmt(FLAGS_ALL_CACHE_KEY))
    if not flags:
        flags = Flag.objects.values_list('name', flat=True)
        cache.add(keyfmt(FLAGS_ALL_CACHE_KEY), flags)
    flag_values = [(f, flag_is_active(request, f)) for f in flags]

    switches = cache.get(keyfmt(SWITCHES_ALL_CACHE_KEY))
    if not switches:
        switches = Switch.objects.values_list('name', 'active')
        cache.add(keyfmt(SWITCHES_ALL_CACHE_KEY), switches)

    samples = cache.get(keyfmt(SAMPLES_ALL_CACHE_KEY))
    if not samples:
        samples = Sample.objects.values_list('name', flat=True)
        cache.add(keyfmt(SAMPLES_ALL_CACHE_KEY), samples)
    sample_values = [(s, sample_is_active(s)) for s in samples]

    flag_default = getattr(settings, 'WAFFLE_FLAG_DEFAULT', False)
    switch_default = getattr(settings, 'WAFFLE_SWITCH_DEFAULT', False)
    sample_default = getattr(settings, 'WAFFLE_SAMPLE_DEFAULT', False)

    return render_to_response('waffle/waffle.js',
                              {
                                'flags': flag_values,
                                'switches': switches,
                                'samples': sample_values,
                                'flag_default': flag_default,
                                'switch_default': switch_default,
                                'sample_default': sample_default,
                              },
                              mimetype='application/x-javascript')
Ejemplo n.º 26
0
    def assert_sample_dynamically_created_with_value(self, is_active,
                                                     expected_value):
        SAMPLE_NAME = 'my_dynamically_created_sample'

        assert Sample.objects.count() == 0
        assert is_active == waffle.sample_is_active(SAMPLE_NAME)
        assert Sample.objects.count() == 1

        sample = Sample.objects.get(name=SAMPLE_NAME)

        assert sample.name == SAMPLE_NAME
        assert sample.percent == expected_value

        # We assert no queries are made to ensure samples created when the
        # `CREATE_MISSING_SAMPLES` setting is active are properly cached.
        with self.assertNumQueries(0):
            assert is_active == waffle.sample_is_active(SAMPLE_NAME)
Ejemplo n.º 27
0
def wafflejs(request):
    flag_values = [(f, flag_is_active(request, f)) for f in get_all_flag_names()]
    sample_values = [(s, sample_is_active(s)) for s in get_all_sample_names()]

    return render_to_response('waffle/waffle.js', {'flags': flag_values,
                                                   'switches': get_all_switch_tuples(),
                                                   'samples': sample_values},
                              mimetype='application/x-javascript')
Ejemplo n.º 28
0
def root(request, format=None, **kwargs):
    """
    The documentation for the Open Science Framework API can be found at [developer.osf.io](https://developer.osf.io).
    The contents of this endpoint are variable and subject to change without notification.
    """
    if request.user and not request.user.is_anonymous:
        user = request.user
        current_user = UserSerializer(user, context={'request': request}).data
    else:
        current_user = None

    flags = [
        name for name in Flag.objects.values_list('name', flat=True)
        if flag_is_active(request, name)
    ]
    samples = [
        name for name in Sample.objects.values_list('name', flat=True)
        if sample_is_active(name)
    ]
    switches = list(
        Switch.objects.filter(active=True).values_list('name', flat=True))

    kwargs = request.parser_context['kwargs']
    return_val = {
        'meta': {
            'message': 'Welcome to the OSF API.',
            'version': request.version,
            'current_user': current_user,
            'active_flags': flags + samples + switches,
        },
        'links': {
            'nodes':
            utils.absolute_reverse('nodes:node-list', kwargs=kwargs),
            'users':
            utils.absolute_reverse('users:user-list', kwargs=kwargs),
            'collections':
            utils.absolute_reverse('collections:collection-list',
                                   kwargs=kwargs),
            'registrations':
            utils.absolute_reverse('registrations:registration-list',
                                   kwargs=kwargs),
            'institutions':
            utils.absolute_reverse('institutions:institution-list',
                                   kwargs=kwargs),
            'licenses':
            utils.absolute_reverse('licenses:license-list', kwargs=kwargs),
            'schemas':
            utils.absolute_reverse('schemas:registration-schema-list',
                                   kwargs=kwargs),
            'addons':
            utils.absolute_reverse('addons:addon-list', kwargs=kwargs),
        },
    }

    if utils.has_admin_scope(request):
        return_val['meta']['admin'] = True

    return Response(return_val)
Ejemplo n.º 29
0
def call_signing(file_obj):
    """Get the jar signature and send it to the signing server to be signed."""
    log.debug('Calling autograph service: {0}'.format(
        settings.AUTOGRAPH_CONFIG['server_url']))

    if waffle.sample_is_active('activate-autograph-file-signing'):
        return autograph_sign_file(file_obj)

    return autograph_sign_data(file_obj)
Ejemplo n.º 30
0
def call_signing(file_obj):
    """Get the jar signature and send it to the signing server to be signed."""
    log.debug('Calling autograph service: {0}'.format(
        settings.AUTOGRAPH_CONFIG['server_url']))

    if waffle.sample_is_active('activate-autograph-file-signing'):
        return autograph_sign_file(file_obj)

    return autograph_sign_data(file_obj)
Ejemplo n.º 31
0
    def assert_sample_dynamically_created_with_value(self, is_active, expected_value):
        SAMPLE_NAME = 'my_dynamically_created_sample'

        assert Sample.objects.count() == 0
        assert is_active == waffle.sample_is_active(SAMPLE_NAME)
        assert Sample.objects.count() == 1

        sample = Sample.objects.get(name=SAMPLE_NAME)

        assert sample.name == SAMPLE_NAME
        assert sample.percent == expected_value
Ejemplo n.º 32
0
    def test_active_signal(self):
        sample = Sample.objects.create(name='sample', percent='100.0')

        def handler(sender, **kwargs):
            self.evaluated = kwargs['active']
        try:
            sample_evaluated.connect(handler)
            assert waffle.sample_is_active(sample.name)
            assert self.evaluated
        finally:
            sample_evaluated.disconnect(handler)
Ejemplo n.º 33
0
def search_suggestions(request):
    if waffle.sample_is_active('autosuggest-throttle'):
        return HttpResponse(status=503)
    cat = request.GET.get('cat', 'all')
    suggesterClass = {
        'all': AddonSuggestionsAjax,
        'themes': PersonaSuggestionsAjax,
    }.get(cat, AddonSuggestionsAjax)
    items = suggesterClass(request, ratings=True).items
    for s in items:
        s['rating'] = float(s['rating'])
    return {'suggestions': items}
Ejemplo n.º 34
0
def search_suggestions(request):
    if waffle.sample_is_active('autosuggest-throttle'):
        return HttpResponse(status=503)
    cat = request.GET.get('cat', 'all')
    suggesterClass = {
        'all': AddonSuggestionsAjax,
        'themes': PersonaSuggestionsAjax,
    }.get(cat, AddonSuggestionsAjax)
    items = suggesterClass(request, ratings=True).items
    for s in items:
        s['rating'] = float(s['rating'])
    return {'suggestions': items}
Ejemplo n.º 35
0
def recommendations(request, version, platform, limit=9):
    """
    Figure out recommended add-ons for an anonymous user based on POSTed guids.

    POST body looks like {"guids": [...]} with an optional "token" key if
    they've been here before.
    """
    try:
        POST = json.loads(request.raw_post_data)
        guids = POST['guids']
    except (ValueError, TypeError, KeyError):
        # Errors: invalid json, didn't get a dict, didn't find "guids".
        return http.HttpResponseBadRequest()

    addon_ids = get_addon_ids(guids)
    index = Collection.make_index(addon_ids)

    ids, recs = Collection.get_recs_from_ids(addon_ids, request.APP, version)
    recs = _recommendations(request, version, platform, limit,
                            index, ids, recs)

    # We're only storing a percentage of the collections we see because the db
    # can't keep up with 100%.
    if not waffle.sample_is_active('disco-pane-store-collections'):
        return recs

    # Users have a token2 if they've been here before. The token matches
    # addon_index in their SyncedCollection.
    if 'token2' in POST:
        token = POST['token2']
        if token == index:
            # We've seen them before and their add-ons have not changed.
            return recs
        elif token != index:
            # We've seen them before and their add-ons changed. Remove the
            # reference to their old synced collection.
            (SyncedCollection.objects.filter(addon_index=index)
             .update(count=F('count') - 1))

    # Try to create the SyncedCollection. There's a unique constraint on
    # addon_index so it will fail if this addon_index already exists. If we
    # checked for existence first and then created a collection there would
    # be a race condition between multiple users with the same addon_index.
    try:
        c = SyncedCollection.objects.create(addon_index=index, count=1)
        c.set_addons(addon_ids)
    except IntegrityError:
        try:
            (SyncedCollection.objects.filter(addon_index=index)
             .update(count=F('count') + 1))
        except Exception, e:
            log.error(u'Could not count++ "%s" (%s).' % (index, e))
Ejemplo n.º 36
0
def recommendations(request, version, platform, limit=9):
    """
    Figure out recommended add-ons for an anonymous user based on POSTed guids.

    POST body looks like {"guids": [...]} with an optional "token" key if
    they've been here before.
    """
    try:
        POST = json.loads(request.raw_post_data)
        guids = POST['guids']
    except (ValueError, TypeError, KeyError):
        # Errors: invalid json, didn't get a dict, didn't find "guids".
        return http.HttpResponseBadRequest()

    addon_ids = get_addon_ids(guids)
    index = Collection.make_index(addon_ids)

    ids, recs = Collection.get_recs_from_ids(addon_ids, request.APP, version)
    recs = _recommendations(request, version, platform, limit,
                            index, ids, recs)

    # We're only storing a percentage of the collections we see because the db
    # can't keep up with 100%.
    if not waffle.sample_is_active('disco-pane-store-collections'):
        return recs

    # Users have a token2 if they've been here before. The token matches
    # addon_index in their SyncedCollection.
    if 'token2' in POST:
        token = POST['token2']
        if token == index:
            # We've seen them before and their add-ons have not changed.
            return recs
        elif token != index:
            # We've seen them before and their add-ons changed. Remove the
            # reference to their old synced collection.
            (SyncedCollection.objects.filter(addon_index=index)
             .update(count=F('count') - 1))

    # Try to create the SyncedCollection. There's a unique constraint on
    # addon_index so it will fail if this addon_index already exists. If we
    # checked for existence first and then created a collection there would
    # be a race condition between multiple users with the same addon_index.
    try:
        c = SyncedCollection.objects.create(addon_index=index, count=1)
        c.set_addons(addon_ids)
    except IntegrityError:
        try:
            (SyncedCollection.objects.filter(addon_index=index)
             .update(count=F('count') + 1))
        except Exception, e:
            log.error(u'Could not count++ "%s" (%s).' % (index, e))
Ejemplo n.º 37
0
def can_use_enterprise_catalog(enterprise_uuid):
    """
    Function to check if enterprise-catalog endpoints should be hit given an enterprise uuid.

    Checks the USE_ENTERPRISE_CATALOG waffle sample and ensures the passed
    enterprise uuid is not in the ENTERPRISE_CUSTOMERS_EXCLUDED_FROM_CATALOG list.

    Args:
        enterprise_uuid: the unique identifier for an enterprise customer

    Returns:
        boolean: True if sample is active and enterprise is not excluded
                 False if sample not active or enterprise is excluded
    """
    return (waffle.sample_is_active(USE_ENTERPRISE_CATALOG)
            and str(enterprise_uuid) not in getattr(
                settings, 'ENTERPRISE_CUSTOMERS_EXCLUDED_FROM_CATALOG', []))
Ejemplo n.º 38
0
def sample(parser, token):
    try:
        tag, sample_name = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError, \
              "%r tag requires an argument" % token.contents.split()[0]

    sample_name = sample_name.strip('\'"')
    condition = lambda r, n: sample_is_active(n)

    nodelist_true = parser.parse(('else', 'endsample'))
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse(('endsample', ))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()

    return WaffleNode(nodelist_true, nodelist_false, condition, sample_name)
Ejemplo n.º 39
0
def sample(parser, token):
    try:
        tag, sample_name = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError, \
              "%r tag requires an argument" % token.contents.split()[0]

    sample_name = sample_name.strip('\'"')
    condition = lambda r, n: sample_is_active(n)

    nodelist_true = parser.parse(('else', 'endsample'))
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse(('endsample',))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()

    return WaffleNode(nodelist_true, nodelist_false, condition, sample_name)
Ejemplo n.º 40
0
    def handle_successful_order(self, order, request=None):  # pylint: disable=arguments-differ
        """Send a signal so that receivers can perform relevant tasks (e.g., fulfill the order)."""
        audit_log('order_placed',
                  amount=order.total_excl_tax,
                  basket_id=order.basket.id,
                  currency=order.currency,
                  order_number=order.number,
                  user_id=order.user.id,
                  contains_coupon=order.contains_coupon)

        # Check for the user's email opt in preference, defaulting to false if it hasn't been set
        try:
            email_opt_in = BasketAttribute.objects.get(
                basket=order.basket,
                attribute_type=BasketAttributeType.objects.get(
                    name=EMAIL_OPT_IN_ATTRIBUTE),
            ).value_text == 'True'
        except BasketAttribute.DoesNotExist:
            email_opt_in = False

        # create offer assignment for MULTI_USE_PER_CUSTOMER
        self.create_assignments_for_multi_use_per_customer(order)

        # update offer assignment with voucher application
        self.update_assigned_voucher_offer_assignment(order)

        if waffle.sample_is_active('async_order_fulfillment'):
            # Always commit transactions before sending tasks depending on state from the current transaction!
            # There's potential for a race condition here if the task starts executing before the active
            # transaction has been committed; the necessary order doesn't exist in the database yet.
            # See http://celery.readthedocs.org/en/latest/userguide/tasks.html#database-transactions.
            fulfill_order.delay(
                order.number,
                site_code=order.site.siteconfiguration.partner.short_code,
                email_opt_in=email_opt_in)
        else:
            post_checkout.send(sender=self,
                               order=order,
                               request=request,
                               email_opt_in=email_opt_in)

        return order
Ejemplo n.º 41
0
    def handle_successful_order(self, order):
        """Send a signal so that receivers can perform relevant tasks (e.g., fulfill the order)."""
        audit_log('order_placed',
                  amount=order.total_excl_tax,
                  basket_id=order.basket.id,
                  currency=order.currency,
                  order_number=order.number,
                  user_id=order.user.id,
                  contains_coupon=order.contains_coupon)

        if waffle.sample_is_active('async_order_fulfillment'):
            # Always commit transactions before sending tasks depending on state from the current transaction!
            # There's potential for a race condition here if the task starts executing before the active
            # transaction has been committed; the necessary order doesn't exist in the database yet.
            # See http://celery.readthedocs.org/en/latest/userguide/tasks.html#database-transactions.
            fulfill_order.delay(order.number)
        else:
            post_checkout.send(sender=self, order=order)

        return order
Ejemplo n.º 42
0
def wafflejs(request):
    flags = cache.get(FLAGS_ALL_CACHE_KEY)
    if not flags:
        flags = Flag.objects.values_list('name', flat=True)
        cache.add(FLAGS_ALL_CACHE_KEY, flags)
    flag_values = [(f, flag_is_active(request, f)) for f in flags]

    switches = cache.get(SWITCHES_ALL_CACHE_KEY)
    if not switches:
        switches = Switch.objects.values_list('name', 'active')
        cache.add(SWITCHES_ALL_CACHE_KEY, switches)

    samples = cache.get(SAMPLES_ALL_CACHE_KEY)
    if not samples:
        samples = Sample.objects.values_list('name', flat=True)
        cache.add(SAMPLES_ALL_CACHE_KEY, samples)
    sample_values = [(s, sample_is_active(s)) for s in samples]
    return render_to_response('waffle/waffle.js', {'flags': flag_values,
                                                   'switches': switches,
                                                   'samples': sample_values},
                              mimetype='application/x-javascript')
Ejemplo n.º 43
0
def cspreport(request):
    """Accept CSP reports and log them."""
    report = ('blocked-uri', 'violated-directive', 'original-policy')

    if not waffle.sample_is_active('csp-store-reports'):
        return HttpResponse()

    try:
        v = json.loads(request.body)['csp-report']
        # If possible, alter the PATH_INFO to contain the request of the page
        # the error occurred on, spec: http://mzl.la/P82R5y
        meta = request.META.copy()
        meta['PATH_INFO'] = v.get('document-uri', meta['PATH_INFO'])
        v = [(k, v[k]) for k in report if k in v]
        log_cef('CSP Violation', 5, meta, username=request.user,
                signature='CSPREPORT',
                msg='A client reported a CSP violation',
                cs6=v, cs6Label='ContentPolicy')
    except (KeyError, ValueError), e:
        log.debug('Exception in CSP report: %s' % e, exc_info=True)
        return HttpResponseBadRequest()
Ejemplo n.º 44
0
    def handle_successful_order(self, order):
        """Send a signal so that receivers can perform relevant tasks (e.g., fulfill the order)."""
        audit_log(
            'order_placed',
            amount=order.total_excl_tax,
            basket_id=order.basket.id,
            currency=order.currency,
            order_number=order.number,
            user_id=order.user.id
        )

        if waffle.sample_is_active('async_order_fulfillment'):
            # Always commit transactions before sending tasks depending on state from the current transaction!
            # There's potential for a race condition here if the task starts executing before the active
            # transaction has been committed; the necessary order doesn't exist in the database yet.
            # See http://celery.readthedocs.org/en/latest/userguide/tasks.html#database-transactions.
            fulfill_order.delay(order.number)
        else:
            post_checkout.send(sender=self, order=order)

        return order
Ejemplo n.º 45
0
def root(request, format=None, **kwargs):
    """
    The documentation for the Open Science Framework API can be found at [developer.osf.io](https://developer.osf.io).
    The contents of this endpoint are variable and subject to change without notification.
    """
    if request.user and not request.user.is_anonymous:
        user = request.user
        current_user = UserSerializer(user, context={'request': request}).data
    else:
        current_user = None

    flags = [name for name in Flag.objects.values_list('name', flat=True) if flag_is_active(request, name)]
    samples = [name for name in Sample.objects.values_list('name', flat=True) if sample_is_active(name)]
    switches = list(Switch.objects.filter(active=True).values_list('name', flat=True))

    kwargs = request.parser_context['kwargs']
    return_val = {
        'meta': {
            'message': 'Welcome to the OSF API.',
            'version': request.version,
            'current_user': current_user,
            'active_flags': flags + samples + switches,
        },
        'links': {
            'nodes': utils.absolute_reverse('nodes:node-list', kwargs=kwargs),
            'users': utils.absolute_reverse('users:user-list', kwargs=kwargs),
            'collections': utils.absolute_reverse('collections:collection-list', kwargs=kwargs),
            'registrations': utils.absolute_reverse('registrations:registration-list', kwargs=kwargs),
            'institutions': utils.absolute_reverse('institutions:institution-list', kwargs=kwargs),
            'licenses': utils.absolute_reverse('licenses:license-list', kwargs=kwargs),
            'schemas': utils.absolute_reverse('schemas:registration-schema-list', kwargs=kwargs),
            'addons': utils.absolute_reverse('addons:addon-list', kwargs=kwargs),
        },
    }

    if utils.has_admin_scope(request):
        return_val['meta']['admin'] = True

    return Response(return_val)
Ejemplo n.º 46
0
def wafflejs(request):
    flags = cache.get(FLAGS_ALL_CACHE_KEY)
    if not flags:
        flags = Flag.objects.values_list('name', flat=True)
        cache.add(FLAGS_ALL_CACHE_KEY, flags)
    flag_values = [(f, flag_is_active(request, f)) for f in flags]

    switches = cache.get(SWITCHES_ALL_CACHE_KEY)
    if not switches:
        switches = Switch.objects.values_list('name', 'active')
        cache.add(SWITCHES_ALL_CACHE_KEY, switches)

    samples = cache.get(SAMPLES_ALL_CACHE_KEY)
    if not samples:
        samples = Sample.objects.values_list('name', flat=True)
        cache.add(SAMPLES_ALL_CACHE_KEY, samples)
    sample_values = [(s, sample_is_active(s)) for s in samples]
    return render_to_response('waffle/waffle.js', {
        'flags': flag_values,
        'switches': switches,
        'samples': sample_values
    },
                              mimetype='application/x-javascript')
Ejemplo n.º 47
0
def cspreport(request):
    """Accept CSP reports and log them."""
    report = ('blocked-uri', 'violated-directive', 'original-policy')

    if not waffle.sample_is_active('csp-store-reports'):
        return HttpResponse()

    try:
        v = json.loads(request.raw_post_data)['csp-report']
        # CEF module wants a dictionary of environ, we want request
        # to be the page with error on it, that's contained in the csp-report
        # so we need to modify the meta before we pass in to the logger
        meta = request.META.copy()
        method, url = v['request'].split(' ', 1)
        meta.update({'REQUEST_METHOD': method, 'PATH_INFO': url})
        v = [(k, v[k]) for k in report if k in v]
        log_cef('CSP Violation', 5, meta, username=request.user,
                signature='CSPREPORT',
                msg='A client reported a CSP violation',
                cs7=v, cs7Label='ContentPolicy')
    except Exception, e:
        log.debug('Exception in CSP report: %s' % e, exc_info=True)
        return HttpResponseBadRequest()
Ejemplo n.º 48
0
def cspreport(request):
    """Accept CSP reports and log them."""
    report = ('blocked-uri', 'violated-directive', 'original-policy')

    if not waffle.sample_is_active('csp-store-reports'):
        return HttpResponse()

    try:
        v = json.loads(request.raw_post_data)['csp-report']
        # CEF module wants a dictionary of environ, we want request
        # to be the page with error on it, that's contained in the csp-report.
        meta = request.META.copy()
        method, url = v['request'].split(' ', 1)
        meta.update({'REQUEST_METHOD': method, 'PATH_INFO': url})
        v = [(k, v[k]) for k in report if k in v]
        # This requires you to use the cef.formatter to get something nice out.
        csp_log.warning('Violation', dict(environ=meta,
                                          product='addons',
                                          username=request.user,
                                          data=v))
    except Exception:
        return HttpResponseBadRequest()

    return HttpResponse()
Ejemplo n.º 49
0
def cspreport(request):
    """Accept CSP reports and log them."""
    report = ('blocked-uri', 'violated-directive', 'original-policy')

    if not waffle.sample_is_active('csp-store-reports'):
        return HttpResponse()

    try:
        v = json.loads(request.raw_post_data)['csp-report']
        # CEF module wants a dictionary of environ, we want request
        # to be the page with error on it, that's contained in the csp-report.
        meta = request.META.copy()
        method, url = v['request'].split(' ', 1)
        meta.update({'REQUEST_METHOD': method, 'PATH_INFO': url})
        v = [(k, v[k]) for k in report if k in v]
        # This requires you to use the cef.formatter to get something nice out.
        csp_log.warning('Violation', dict(environ=meta,
                                          product='addons',
                                          username=request.user,
                                          data=v))
    except Exception:
        return HttpResponseBadRequest()

    return HttpResponse()
Ejemplo n.º 50
0
 def test_logging_missing_sample(self, mock_logger):
     waffle.sample_is_active('foo')
     mock_logger.log.assert_called_with(logging.WARNING,
                                        'Sample %s not found', 'foo')
Ejemplo n.º 51
0
 def test_undefined_default(self):
     assert waffle.sample_is_active('foo')
Ejemplo n.º 52
0
 def test_undefined(self):
     assert not waffle.sample_is_active('foo')
Ejemplo n.º 53
0
 def test_undefined_default(self):
     assert waffle.sample_is_active('foo')
Ejemplo n.º 54
0
 def toggle_is_active(self, sample):
     return waffle.sample_is_active(sample.name)
Ejemplo n.º 55
0
def sampleall(parser, token):
    return WaffleNode.handle_token(
        parser, token, 'sampleall',
        lambda request, name: sample_is_active(name), all)
Ejemplo n.º 56
0
 def test_undefined(self):
     assert not waffle.sample_is_active('foo')