Esempio n. 1
0
    def post(self, request, course_id):
        """Takes the form submission from the page and parses it.

        Args:
            request (`Request`): The Django Request object.
            course_id (unicode): The slash-separated course key.

        Returns:
            Status code 400 when the requested mode is unsupported. When the honor mode
            is selected, redirects to the dashboard. When the verified mode is selected,
            returns error messages if the indicated contribution amount is invalid or
            below the minimum, otherwise redirects to the verification flow.

        """
        course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
        user = request.user

        # This is a bit redundant with logic in student.views.change_enrollment,
        # but I don't really have the time to refactor it more nicely and test.
        course = modulestore().get_course(course_key)
        if not has_access(user, 'enroll', course):
            error_msg = _("Enrollment is closed")
            return self.get(request, course_id, error=error_msg)

        requested_mode = self._get_requested_mode(request.POST)

        allowed_modes = CourseMode.modes_for_course_dict(course_key)
        if requested_mode not in allowed_modes:
            return HttpResponseBadRequest(_("Enrollment mode not supported"))

        if requested_mode == 'honor':
            # The user will have already been enrolled in the honor mode at this
            # point, so we just redirect them to the dashboard, thereby avoiding
            # hitting the database a second time attempting to enroll them.
            return redirect(reverse('dashboard'))

        mode_info = allowed_modes[requested_mode]

        if requested_mode == 'verified':
            amount = request.POST.get("contribution") or \
                request.POST.get("contribution-other-amt") or 0

            try:
                # Validate the amount passed in and force it into two digits
                amount_value = decimal.Decimal(amount).quantize(
                    decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)
            except decimal.InvalidOperation:
                error_msg = _("Invalid amount selected.")
                return self.get(request, course_id, error=error_msg)

            # Check for minimum pricing
            if amount_value < mode_info.min_price:
                error_msg = _(
                    "No selected price or selected price is too low.")
                return self.get(request, course_id, error=error_msg)

            donation_for_course = request.session.get("donation_for_course",
                                                      {})
            donation_for_course[unicode(course_key)] = amount_value
            request.session["donation_for_course"] = donation_for_course

            return redirect(
                reverse('verify_student_start_flow',
                        kwargs={'course_id': unicode(course_key)}))
def send_goods_branch(request):
    if request.user.id is None:
        return HttpResponseBadRequest()
    return HttpResponse(get_branch_goods_json(request.user.id),
                        content_type="application/json")
Esempio n. 3
0
def notify_callback(request):
    payment_module = config_get_group('PAYMENT_DOTPAY')
    if payment_module.LIVE.value:
        log.debug("Live IPN on %s", payment_module.KEY.value)
        signature_code = payment_module.MERCHANT_SIGNATURE_CODE.value
        terminal = payment_module.MERCHANT_TERMINAL.value
    else:
        log.debug("Test IPN on %s", payment_module.KEY.value)
        signature_code = payment_module.MERCHANT_TEST_SIGNATURE_CODE.value
        terminal = payment_module.MERCHANT_TEST_TERMINAL.value
    data = request.POST
    log.debug("Transaction data: " + repr(data))
    try:
        #        sig_data = "%s%s%s%s%s%s" % (
        #                data['Ds_Amount'],
        #                data['Ds_Order'],
        #                data['Ds_MerchantCode'],
        #                data['Ds_Currency'],
        #                data['Ds_Response'],
        #                signature_code
        #                )
        #        sig_calc = sha1(sig_data).hexdigest()
        #        if sig_calc != data['Ds_Signature'].lower():
        #            log.error("Invalid signature. Received '%s', calculated '%s'." % (data['Ds_Signature'], sig_calc))
        #            return HttpResponseBadRequest("Checksum error")
        #        if data['Ds_MerchantCode'] != payment_module.DOTPAY_DOTID.value:
        #            log.error("Invalid FUC code: %s" % data['Ds_MerchantCode'])
        #            return HttpResponseNotFound("Unknown FUC code")
        if int(data['t_status']) != 2:
            log.error("Payment not accepted number: %s" % data['t_status'])
            return HttpResponseNotFound("Platnosc odrzucona")
        # TODO: fields Ds_Currency, Ds_SecurePayment may be worth checking

        #xchg_order_id = data['control']
        try:
            #order_id = xchg_order_id[:xchg_order_id.index('T')]
            order_id = data['control']
        except ValueError:
            log.error("Incompatible order ID: '%s'" % order_id)
            return HttpResponseNotFound("Order not found")
        try:
            order = Order.objects.get(id=order_id)
        except Order.DoesNotExist:
            log.error("Received data for nonexistent Order #%s" % order_id)
            return HttpResponseNotFound("Order not found")
        amount = Decimal(data['amount'])


#        if int(data['Ds_Response']) > 100:
#            log.info("Response code is %s. Payment not accepted." % data['Ds_Response'])
#            return HttpResponse()
    except KeyError:
        log.error("Received incomplete DOTPAY transaction data")
        return HttpResponseBadRequest("Incomplete data")
    # success
    order.add_status(status='New', notes=u"Paid through DOTPAY.")
    processor = get_processor_by_key('PAYMENT_DOTPAY')
    payment = processor.record_payment(order=order,
                                       amount=amount,
                                       transaction_id=data['t_id'])
    # empty customer's carts
    for cart in Cart.objects.filter(customer=order.contact):
        cart.empty()
    return HttpResponse()
Esempio n. 4
0
    def process_request(self, request):
        """Process the given request"""
        asset_path = request.path

        if self.is_asset_request(request):
            # Make sure we can convert this request into a location.
            if AssetLocator.CANONICAL_NAMESPACE in asset_path:
                asset_path = asset_path.replace('block/', 'block@', 1)

            # If this is a versioned request, pull out the digest and chop off the prefix.
            requested_digest = None
            if StaticContent.is_versioned_asset_path(asset_path):
                requested_digest, asset_path = StaticContent.parse_versioned_asset_path(
                    asset_path)

            # Make sure we have a valid location value for this asset.
            try:
                loc = StaticContent.get_location_from_path(asset_path)
            except (InvalidLocationError, InvalidKeyError):
                return HttpResponseBadRequest()

            # Attempt to load the asset to make sure it exists, and grab the asset digest
            # if we're able to load it.
            actual_digest = None
            try:
                content = self.load_asset_from_location(loc)
                actual_digest = getattr(content, "content_digest", None)
            except (ItemNotFoundError, NotFoundError):
                return HttpResponseNotFound()

            # If this was a versioned asset, and the digest doesn't match, redirect
            # them to the actual version.
            if requested_digest is not None and actual_digest is not None and (
                    actual_digest != requested_digest):
                actual_asset_path = StaticContent.add_version_to_asset_path(
                    asset_path, actual_digest)
                return HttpResponsePermanentRedirect(actual_asset_path)

            # Set the basics for this request. Make sure that the course key for this
            # asset has a run, which old-style courses do not.  Otherwise, this will
            # explode when the key is serialized to be sent to NR.
            safe_course_key = loc.course_key
            if safe_course_key.run is None:
                safe_course_key = safe_course_key.replace(run='only')

            if newrelic:
                newrelic.agent.add_custom_parameter('course_id',
                                                    safe_course_key)
                newrelic.agent.add_custom_parameter('org', loc.org)
                newrelic.agent.add_custom_parameter('contentserver.path',
                                                    loc.path)

                # Figure out if this is a CDN using us as the origin.
                is_from_cdn = StaticContentServer.is_cdn_request(request)
                newrelic.agent.add_custom_parameter('contentserver.from_cdn',
                                                    is_from_cdn)

                # Check if this content is locked or not.
                locked = self.is_content_locked(content)
                newrelic.agent.add_custom_parameter('contentserver.locked',
                                                    locked)

            # Check that user has access to the content.
            if not self.is_user_authorized(request, content, loc):
                return HttpResponseForbidden('Unauthorized')

            # Figure out if the client sent us a conditional request, and let them know
            # if this asset has changed since then.
            last_modified_at_str = content.last_modified_at.strftime(
                HTTP_DATE_FORMAT)
            if 'HTTP_IF_MODIFIED_SINCE' in request.META:
                if_modified_since = request.META['HTTP_IF_MODIFIED_SINCE']
                if if_modified_since == last_modified_at_str:
                    return HttpResponseNotModified()

            # *** File streaming within a byte range ***
            # If a Range is provided, parse Range attribute of the request
            # Add Content-Range in the response if Range is structurally correct
            # Request -> Range attribute structure: "Range: bytes=first-[last]"
            # Response -> Content-Range attribute structure: "Content-Range: bytes first-last/totalLength"
            # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
            response = None
            if request.META.get('HTTP_RANGE'):
                # If we have a StaticContent, get a StaticContentStream.  Can't manipulate the bytes otherwise.
                if isinstance(content, StaticContent):
                    content = AssetManager.find(loc, as_stream=True)

                header_value = request.META['HTTP_RANGE']
                try:
                    unit, ranges = parse_range_header(header_value,
                                                      content.length)
                except ValueError as exception:
                    # If the header field is syntactically invalid it should be ignored.
                    log.exception(u"%s in Range header: %s for content: %s",
                                  text_type(exception), header_value,
                                  unicode(loc))
                else:
                    if unit != 'bytes':
                        # Only accept ranges in bytes
                        log.warning(
                            u"Unknown unit in Range header: %s for content: %s",
                            header_value, text_type(loc))
                    elif len(ranges) > 1:
                        # According to Http/1.1 spec content for multiple ranges should be sent as a multipart message.
                        # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.16
                        # But we send back the full content.
                        log.warning(
                            u"More than 1 ranges in Range header: %s for content: %s",
                            header_value, text_type(loc))
                    else:
                        first, last = ranges[0]

                        if 0 <= first <= last < content.length:
                            # If the byte range is satisfiable
                            response = HttpResponse(
                                content.stream_data_in_range(first, last))
                            response[
                                'Content-Range'] = b'bytes {first}-{last}/{length}'.format(
                                    first=first,
                                    last=last,
                                    length=content.length)
                            response['Content-Length'] = str(last - first + 1)
                            response.status_code = 206  # Partial Content

                            if newrelic:
                                newrelic.agent.add_custom_parameter(
                                    'contentserver.ranged', True)
                        else:
                            log.warning(
                                u"Cannot satisfy ranges in Range header: %s for content: %s",
                                header_value, text_type(loc))
                            return HttpResponse(
                                status=416)  # Requested Range Not Satisfiable

            # If Range header is absent or syntactically invalid return a full content response.
            if response is None:
                response = HttpResponse(content.stream_data())
                response['Content-Length'] = content.length

            if newrelic:
                newrelic.agent.add_custom_parameter(
                    'contentserver.content_len', content.length)
                newrelic.agent.add_custom_parameter(
                    'contentserver.content_type', content.content_type)

            # "Accept-Ranges: bytes" tells the user that only "bytes" ranges are allowed
            response['Accept-Ranges'] = 'bytes'
            response['Content-Type'] = content.content_type
            response['X-Frame-Options'] = 'ALLOW'

            # Set any caching headers, and do any response cleanup needed.  Based on how much
            # middleware we have in place, there's no easy way to use the built-in Django
            # utilities and properly sanitize and modify a response to ensure that it is as
            # cacheable as possible, which is why we do it ourselves.
            self.set_caching_headers(content, response)

            return response
Esempio n. 5
0
def batch_edit_translations(request):
    try:
        l = request.POST['locale']
        action = request.POST['action']
        entity_pks = utils.split_ints(request.POST.get('entities', ''))
    except MultiValueDictKeyError as e:
        return HttpResponseBadRequest('Bad Request: {error}'.format(error=e))

    locale = get_object_or_404(Locale, code=l)

    entities = (Entity.objects.filter(
        pk__in=entity_pks).prefetch_resources_translations(locale))

    if not entities.exists():
        return JsonResponse({'count': 0})

    # Batch editing is only available to translators.
    # Check if user has translate permissions for all of the projects in passed entities.
    projects = Project.objects.filter(pk__in=entities.values_list(
        'resource__project__pk', flat=True).distinct())
    for project in projects:
        if not request.user.can_translate(project=project, locale=locale):
            return HttpResponseForbidden(
                "Forbidden: You don't have permission for batch editing")

    translation_pks = set()

    for entity in entities:
        if entity.string_plural == "":
            translation_pks.add(entity.get_translation()['pk'])

        else:
            for plural_form in range(0, locale.nplurals or 1):
                translation_pks.add(entity.get_translation(plural_form)['pk'])

    translation_pks.discard(None)
    translations = Translation.objects.filter(pk__in=translation_pks)
    latest_translation_pk = None
    changed_translation_pks = []

    # Must be executed before translations set changes, which is why
    # we need to force evaluate QuerySets by wrapping them inside list()
    def get_translations_info(translations, changed_entities=None):
        count = translations.count()
        translated_resources = list(translations.translated_resources(locale))

        if changed_entities is None:
            changed_entities = list(
                Entity.objects.filter(translation__in=translations).distinct())

        return count, translated_resources, changed_entities

    if action == 'approve':
        approved = translations.filter(approved=False)
        changed_translation_pks = list(approved.values_list('pk', flat=True))
        if changed_translation_pks:
            latest_translation_pk = approved.last().pk
        count, translated_resources, changed_entities = get_translations_info(
            approved)
        approved.update(
            approved=True,
            approved_user=request.user,
            approved_date=timezone.now(),
            rejected=False,
            rejected_user=None,
            rejected_date=None,
            fuzzy=False,
        )

        # Reject all other non-rejected translations.
        suggestions = Translation.objects.filter(
            locale=locale,
            entity__pk__in=entities,
            approved=False,
            rejected=False,
        )
        suggestions.update(
            rejected=True,
            rejected_user=request.user,
            rejected_date=timezone.now(),
            fuzzy=False,
        )

    elif action == 'reject':
        suggestions = Translation.objects.filter(locale=locale,
                                                 entity__pk__in=entities,
                                                 approved=False,
                                                 rejected=False)
        count, translated_resources, changed_entities = get_translations_info(
            suggestions, [])
        TranslationMemoryEntry.objects.filter(
            translation__in=suggestions).delete()
        suggestions.update(
            rejected=True,
            rejected_user=request.user,
            rejected_date=timezone.now(),
            fuzzy=False,
        )

    elif action == 'replace':
        find = request.POST.get('find')
        replace = request.POST.get('replace')

        try:
            translations, changed_translations = translations.find_and_replace(
                find, replace, request.user)
            changed_translation_pks = [c.pk for c in changed_translations]
            if changed_translation_pks:
                latest_translation_pk = max(changed_translation_pks)
        except Translation.NotAllowed:
            return JsonResponse({
                'error': 'Empty translations not allowed',
            })

        count, translated_resources, changed_entities = get_translations_info(
            translations)

    if count == 0:
        return JsonResponse({'count': 0})

    # Update stats
    for translated_resource in translated_resources:
        translated_resource.calculate_stats(save=False)

    bulk_update(translated_resources,
                update_fields=[
                    'total_strings',
                    'approved_strings',
                    'fuzzy_strings',
                    'translated_strings',
                ])

    project = entity.resource.project
    project.aggregate_stats()
    locale.aggregate_stats()
    ProjectLocale.objects.get(locale=locale, project=project).aggregate_stats()

    # Mark translations as changed
    changed_entities_array = []
    existing = ChangedEntityLocale.objects.values_list('entity',
                                                       'locale').distinct()
    for changed_entity in changed_entities:
        key = (changed_entity.pk, locale.pk)

        # Remove duplicate changes to prevent unique constraint violation
        if key not in existing:
            changed_entities_array.append(
                ChangedEntityLocale(entity=changed_entity, locale=locale))
    ChangedEntityLocale.objects.bulk_create(changed_entities_array)

    # Update latest translation
    if latest_translation_pk:
        Translation.objects.get(
            pk=latest_translation_pk).update_latest_translation()

    # Update translation memory
    memory_entries = [
        TranslationMemoryEntry(
            source=t.entity.string,
            target=t.string,
            locale=locale,
            entity=t.entity,
            translation=t,
            project=project,
        ) for t in (Translation.objects.filter(pk__in=changed_translation_pks).
                    prefetch_related('entity__resource'))
    ]
    TranslationMemoryEntry.objects.bulk_create(memory_entries)

    return JsonResponse({'count': count})
Esempio n. 6
0
 def get(self, request, *args, **kwargs):
     self.parse_params()
     if self.section and (self.section not in self.search_sections):
         message = 'The section {0} was not known'
         return HttpResponseBadRequest(message.format(self.section))
     return super(SearchBaseView, self).get(request, *args, **kwargs)
Esempio n. 7
0
 def form_invalid(self, form):
     return HttpResponseBadRequest(json.dumps(dict(errors=form.errors)),
                                   content_type='application/json')
    def admin_upload_view(self, request, id=None):
        if id:
            object = self.get_object(request, id)
        else:
            object = None
        if request.method == 'POST':    # POST data
            if not ("f" in request.GET.keys()):  # upload file
                if not request.FILES:
                    return HttpResponseBadRequest('Must upload a file')

                # get the uploaded file
                files = request.FILES.getlist(u'files[]')
                resp = []

                for f in files:
                    error = False

                    # file size
                    if f.size > self.upload_options["maxfilesize"]:
                        error = "maxFileSize"
                    if f.size < self.upload_options["minfilesize"]:
                        error = "minFileSize"

                    # allowed file type
                    acceptedformats = self.upload_options["acceptedformats"]
                    # Allow any mimetype if we set the value to be ("*",)
                    if acceptedformats!=("*",):
                        if f.content_type not in acceptedformats:
                            error = "acceptFileTypes"

                    # the response data which will be returned to
                    # the uploader as json
                    response_data = {
                        "name": f.name,
                        "size": f.size,
                        "type": f.content_type,
                        "delete_type": "POST",
                    }

                    # if there was an error, add error message
                    # to response_data and return
                    if error:
                        # append error message
                        response_data["error"] = error
                        # generate json
                    else:
                        while 1:
                            chunk = f.file.read(10000)
                            if not chunk:
                                break
                        f.file.seek(0)

                        # Manipulate file.
                        data = self.process_uploaded_file(f, object,
                                                          request)

                        assert 'id' in data, 'Must return id in data'
                        response_data.update(data)
                        response_data['delete_url'] = request.path + "?"\
                            + urllib.urlencode({'f': data['id']})

                    resp.append(response_data)

                # generate the json data
                response_data = json.dumps(resp)
                # response type
                response_type = "application/json"

                # QUIRK HERE
                # in jQuey uploader, when it falls back to uploading
                # using iFrames
                # the response content type has to be text/html
                # if json will be send, error will occur
                # if iframe is sending the request, it's headers are
                # a little different compared
                # to the jQuery ajax request
                # they have different set of HTTP_ACCEPT values
                # so if the text/html is present, file was uploaded
                # using jFrame because
                # that value is not in the set when uploaded by XHR
                if "text/html" in request.META["HTTP_ACCEPT"]:
                    response_type = "text/html"
                response_type = "text/html"

                # return the data to the uploading plugin
                return HttpResponse(response_data, content_type=response_type)

            else:
                # file has to be deleted
                # get the file path by getting it from the query
                # (e.g. '?f=filename.here')
                self.delete_file(request.GET["f"], request)

                # generate true json result
                # in this case is it a json True value
                # if true is not returned, the file will not be
                # removed from the upload queue
                response_data = json.dumps(True)

                # return the result data
                # here it always has to be json
                return HttpResponse(response_data, content_type="application/json")

        else:
            #GET
            context = {
                # these two are necessary to generate the jQuery templates
                # they have to be included here since they conflict
                #  with django template system
                "open_tv": u'{{',
                "close_tv": u'}}',
                # some of the parameters to be checked by javascript
                "maxfilesize": self.upload_options["maxfilesize"],
                "minfilesize": self.upload_options["minfilesize"],
                # django admin parameters
                "object": object,
                'media': self.media,
                'opts': self.model._meta,
                'change': False,
                'is_popup': 'pop' in request.GET,
                'add': True,
                'app_label': self.model._meta.app_label,
                'save_as': 'teste',
                'has_delete_permission': False,
                'has_add_permission': False,
                'has_change_permission': False,
            }

            return render(request,
                          self.multiupload_template,
                          context,
                          )
Esempio n. 9
0
def create_transaction(request, event_id):
    data = json.loads(request.body)
    try:
        buy = (data['buy'] == 'True')  # kupno, sprzedaz
        outcome = data['outcome']  # tak nie
        for_price = data['for_price']  # cena
    except:
        return HttpResponseBadRequest(
            _("Something went wrong, try again in a \
                                        few seconds."))
    try:
        if buy:
            user, event, bet = Bet.objects.buy_a_bet(request.user, event_id,
                                                     outcome, for_price)
        else:
            user, event, bet = Bet.objects.sell_a_bet(request.user, event_id,
                                                      outcome, for_price)
    except NonexistantEvent:
        raise Http404
    except PriceMismatch as e:
        result = {
            'error': unicode(e.message.decode('utf-8')),
            'updates': {
                'events': [e.updated_event.event_dict]
            }
        }
        return JSONResponseBadRequest(json.dumps(result))
    except InsufficientCash as e:
        result = {
            'error': unicode(e.message.decode('utf-8')),
            'updates': {
                'user': [e.updated_user.statistics_dict]
            }
        }

        return JSONResponseBadRequest(json.dumps(result))
    except InsufficientBets as e:
        result = {
            'error': unicode(e.message.decode('utf-8')),
            'updates': {
                'bets': [e.updated_bet.bet_dict]
            }
        }

        return JSONResponseBadRequest(json.dumps(result))
    except EventNotInProgress as e:
        result = {
            'error': unicode(e.message.decode('utf-8')),
        }

        return JSONResponseBadRequest(json.dumps(result))
    except UnknownOutcome as e:
        result = {
            'error': unicode(e.message.decode('utf-8')),
        }

        return JSONResponseBadRequest(json.dumps(result))

    result = {
        'updates': {
            'bets': [bet.bet_dict],
            'events': [event.event_dict],
            'user': user.statistics_dict
        }
    }

    return JSONResponse(json.dumps(result))
Esempio n. 10
0
 def bad_request(self, data=''):
     return HttpResponseBadRequest(data)
Esempio n. 11
0
def edit_app_attr(request, domain, app_id, attr):
    """
    Called to edit any (supported) app attribute, given by attr

    """
    app = get_app(domain, app_id)

    try:
        hq_settings = json.loads(request.body)['hq']
    except ValueError:
        hq_settings = request.POST

    attributes = [
        'all',
        'recipients',
        'name',
        'text_input',
        'platform',
        'build_spec',
        'use_custom_suite',
        'custom_suite',
        'admin_password',
        'comment',
        'use_j2me_endpoint',
        # Application only
        'cloudcare_enabled',
        'case_sharing',
        'translation_strategy',
        'auto_gps_capture',
        # RemoteApp only
        'profile_url',
        'manage_urls',
        'mobile_ucr_restore_version',
    ]
    if attr not in attributes:
        return HttpResponseBadRequest()

    def should_edit(attribute):
        return attribute == attr or ('all' == attr
                                     and attribute in hq_settings)

    def parse_sync_interval(interval):
        try:
            return int(interval)
        except ValueError:
            pass

    resp = {"update": {}}
    # For either type of app
    easy_attrs = (
        ('build_spec', BuildSpec.from_string),
        ('practice_mobile_worker_id', None),
        ('case_sharing', None),
        ('cloudcare_enabled', None),
        ('manage_urls', None),
        ('name', None),
        ('platform', None),
        ('recipients', None),
        ('text_input', None),
        ('use_custom_suite', None),
        ('secure_submissions', None),
        ('translation_strategy', None),
        ('auto_gps_capture', None),
        ('use_grid_menus', None),
        ('grid_form_menus', None),
        ('target_commcare_flavor', None),
        ('comment', None),
        ('custom_base_url', None),
        ('use_j2me_endpoint', None),
        ('mobile_ucr_restore_version', None),
        ('location_fixture_restore', None),
    )
    linked_app_attrs = [
        'target_commcare_flavor',
    ]
    for attribute, transformation in easy_attrs:
        if should_edit(attribute):
            value = hq_settings[attribute]
            if transformation:
                value = transformation(value)
            setattr(app, attribute, value)
            if hasattr(app,
                       'linked_app_attrs') and attribute in linked_app_attrs:
                app.linked_app_attrs.update({
                    attribute: value,
                })

    if should_edit("name"):
        clear_app_cache(request, domain)
        name = hq_settings['name']
        resp['update'].update({
            '.variable-app_name':
            name,
            '[data-id="{id}"]'.format(id=app_id):
            ApplicationsTab.make_app_title(name, app.doc_type),
        })

    if should_edit("build_spec"):
        resp['update']['commcare-version'] = app.commcare_minor_release

    if should_edit("practice_mobile_worker_id"):
        user_id = hq_settings['practice_mobile_worker_id']
        if not app.enable_practice_users:
            app.practice_mobile_worker_id = None
        elif user_id:
            get_and_assert_practice_user_in_domain(user_id, request.domain)

    if should_edit("admin_password"):
        admin_password = hq_settings.get('admin_password')
        if admin_password:
            app.set_admin_password(admin_password)

    # For Normal Apps
    if should_edit("cloudcare_enabled"):
        if app.get_doc_type() not in ("Application", ):
            raise Exception("App type %s does not support cloudcare" %
                            app.get_doc_type())
        if not has_privilege(request, privileges.CLOUDCARE):
            app.cloudcare_enabled = False

    def require_remote_app():
        if app.get_doc_type() not in ("RemoteApp", ):
            raise Exception("App type %s does not support profile url" %
                            app.get_doc_type())

    # For RemoteApps
    if should_edit("profile_url"):
        require_remote_app()
        app['profile_url'] = hq_settings['profile_url']
    if should_edit("manage_urls"):
        require_remote_app()

    app.save(resp)
    # this is a put_attachment, so it has to go after everything is saved
    if should_edit("custom_suite"):
        app.set_custom_suite(hq_settings['custom_suite'])

    return HttpResponse(json.dumps(resp))
Esempio n. 12
0
def post_comment_ajax(request, using=None):
    """
    Post a comment, via an Ajax call.
    """
    if not request.is_ajax():
        return HttpResponseBadRequest("Expecting Ajax call")

    # This is copied from django_comments.
    # Basically that view does too much, and doesn't offer a hook to change the rendering.
    # The request object is not passed to next_redirect for example.
    #
    # This is a separate view to integrate both features. Previously this used django-ajaxcomments
    # which is unfortunately not thread-safe (it it changes the comment view per request).

    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name(
            ) or request.user.username
        if not data.get('email', ''):
            data["email"] = request.user.email

    # Look up the object we're trying to comment about
    ctype = data.get("content_type")
    object_pk = data.get("object_pk")
    if ctype is None or object_pk is None:
        return CommentPostBadRequest(
            "Missing content_type or object_pk field.")
    try:
        model = get_django_model(*ctype.split(".", 1))
        target = model._default_manager.using(using).get(pk=object_pk)
    except ValueError:
        return CommentPostBadRequest("Invalid object_pk value: {0}".format(
            escape(object_pk)))
    except TypeError:
        return CommentPostBadRequest("Invalid content_type value: {0}".format(
            escape(ctype)))
    except AttributeError:
        return CommentPostBadRequest(
            "The given content-type {0} does not resolve to a valid model.".
            format(escape(ctype)))
    except ObjectDoesNotExist:
        return CommentPostBadRequest(
            "No object matching content-type {0} and object PK {1} exists.".
            format(escape(ctype), escape(object_pk)))
    except (ValueError, ValidationError) as e:
        return CommentPostBadRequest(
            "Attempting go get content-type {0!r} and object PK {1!r} exists raised {2}"
            .format(escape(ctype), escape(object_pk), e.__class__.__name__))

    # Do we want to preview the comment?
    preview = "preview" in data

    # Construct the comment form
    form = get_comments_form()(target, data=data)

    # Check security information
    if form.security_errors():
        return CommentPostBadRequest(
            "The comment form failed security verification: {0}".format(
                form.security_errors()))

    # If there are errors or if we requested a preview show the comment
    if preview:
        comment = form.get_comment_object() if not form.errors else None
        return _ajax_result(request,
                            form,
                            "preview",
                            comment,
                            object_id=object_pk)
    if form.errors:
        return _ajax_result(request, form, "post", object_id=object_pk)

    # Otherwise create the comment
    comment = form.get_comment_object()
    comment.ip_address = request.META.get("REMOTE_ADDR", None)
    if request.user.is_authenticated():
        comment.user = request.user

    # Signal that the comment is about to be saved
    responses = signals.comment_will_be_posted.send(sender=comment.__class__,
                                                    comment=comment,
                                                    request=request)

    for (receiver, response) in responses:
        if response is False:
            return CommentPostBadRequest(
                "comment_will_be_posted receiver {0} killed the comment".
                format(receiver.__name__))

    # Save the comment and signal that it was saved
    comment.save()
    signals.comment_was_posted.send(sender=comment.__class__,
                                    comment=comment,
                                    request=request)

    return _ajax_result(request, form, "post", comment, object_id=object_pk)
Esempio n. 13
0
 def wrap(request, *args, **kwargs):
     if not request.is_ajax():
         return HttpResponseBadRequest("Bad Request: Request must be AJAX")
     return f(request, *args, **kwargs)
Esempio n. 14
0
 def post(self, request, *args, **kwargs):
     if not self.profile.totp_key:
         return HttpResponseBadRequest(
             'No TOTP key generated on server side?')
     return super(TOTPEnableView, self).post(request, *args, **kwargs)
Esempio n. 15
0
    def put(self, request, file_mgr_name, system_id, file_path):
        fm_cls = FileLookupManager(file_mgr_name)
        fm = fm_cls(None)
        if fm.requires_auth and not request.user.is_authenticated:
            return HttpResponseForbidden('Login Required.')

        post_body = json.loads(request.body)
        metadata = post_body.get('metadata', {})
        if file_mgr_name == 'agave' or not metadata:
            fmgr = AgaveFileManager(
                agave_client=request.user.agave_oauth.client)
            try:
                file_obj = fmgr.listing(system_id, file_path)
                file_obj.metadata.update(metadata)
                file_dict = file_obj.to_dict()
                file_dict['keyword'] = file_obj.metadata.value['keywords']
                metrics.info('Data Depot',
                             extra={
                                 'user':
                                 request.user.username,
                                 'sessionId':
                                 getattr(request.session, 'session_key', ''),
                                 'operation':
                                 'data_depot_metadata_update',
                                 'info': {
                                     'systemId': system_id,
                                     'filePath': file_path,
                                     'metadata': metadata
                                 }
                             })
                event_data = {
                    Notification.EVENT_TYPE: 'data_depot',
                    Notification.OPERATION: 'data_depot_metadata_update',
                    Notification.STATUS: Notification.SUCCESS,
                    Notification.USER: request.user.username,
                    Notification.MESSAGE: 'Metadata was updated successfully.',
                    Notification.EXTRA: {
                        'systemId': system_id,
                        'filePath': file_path,
                        'metadata': metadata
                    }
                }
                Notification.objects.create(**event_data)
            except HTTPError as err:
                logger.debug(err.response.text)
                event_data = {
                    Notification.EVENT_TYPE: 'data_depot',
                    Notification.STATUS: Notification.ERROR,
                    Notification.OPERATION: 'data_depot_metadata_update',
                    Notification.USER: request.user.username,
                    Notification.MESSAGE: 'Metadata was updated successfully.',
                    Notification.EXTRA: {
                        'systemId': system_id,
                        'filePath': file_path,
                        'metadata': metadata
                    }
                }
                Notification.objects.create(**event_data)
            return JsonResponse(file_dict)

        return HttpResponseBadRequest('Unsupported file manager.')
Esempio n. 16
0
 def handle_leave_request(self):
     if self.is_user_in_trip(self.request.user):
         user_id = self.request.POST['user_id']
         self.handle_member_leaving_trip(user_id)
         return HttpResponse(str(reverse('root:home')))
     return HttpResponseBadRequest('User is not in trip')
Esempio n. 17
0
    def get(self, request, file_mgr_name, system_id, file_path):
        if file_mgr_name == AgaveFileManager.NAME \
            or file_mgr_name == 'public' \
            or file_mgr_name == 'community' \
            or file_mgr_name == 'published':
            if not request.user.is_authenticated:
                if file_mgr_name in ['public', 'community', 'published']:
                    ag = get_user_model().objects.get(
                        username='******').agave_oauth.client
                else:
                    return HttpResponseForbidden('Login required')
            else:
                ag = request.user.agave_oauth.client
            fm = AgaveFileManager(agave_client=ag)
            f = fm.listing(system_id, file_path)
            if request.GET.get('preview', False):
                metrics.info('Data Depot',
                             extra={
                                 'user':
                                 request.user.username,
                                 'sessionId':
                                 getattr(request.session, 'session_key', ''),
                                 'operation':
                                 'agave_file_preview',
                                 'info': {
                                     'systemId': system_id,
                                     'filePath': file_path
                                 }
                             })
                context = {'file': f}
                if f.ext in BaseFileResource.SUPPORTED_IMAGE_PREVIEW_EXTS:
                    context['image_preview'] = f.download_postit(force=False,
                                                                 lifetime=360)
                elif f.ext in BaseFileResource.SUPPORTED_TEXT_PREVIEW_EXTS:
                    content = f.download()
                    try:
                        encoded = content
                    except UnicodeError:
                        try:
                            encoding = chardet.detect(content)['encoding']
                            encoded = content.decode(encoding).encode('utf-8')
                        except UnicodeError:
                            logger.exception('Failed to preview file',
                                             extra={
                                                 'file_mgr_name':
                                                 file_mgr_name,
                                                 'system_id': system_id,
                                                 'file_path': file_path
                                             })
                            encoded = 'Sorry! We were unable to preview this file due ' \
                                      'to an unrecognized content encoding. Please ' \
                                      'download the file to view its contents.'
                    context['text_preview'] = encoded
                elif f.ext in BaseFileResource.SUPPORTED_OBJECT_PREVIEW_EXTS:
                    context['object_preview'] = f.download_postit(force=False,
                                                                  lifetime=360)

                elif f.ext in BaseFileResource.SUPPORTED_MS_OFFICE:
                    context['iframe_preview'] = 'https://view.officeapps.live.com/op/view.aspx?src={}'\
                                                .format(f.download_postit(force=False, lifetime=360))
                elif f.ext in BaseFileResource.SUPPORTED_VIDEO_EXTS:
                    context['video_preview'] = f.download_postit(force=False,
                                                                 lifetime=360)
                    context[
                        'mimetype'] = BaseFileResource.SUPPORTED_VIDEO_MIMETYPES[
                            f.ext]

                return render(request,
                              'designsafe/apps/api/agave/preview.html',
                              context)
            else:
                url = 'https://agave.designsafe-ci.org/files/v2/media/{system}/{path}'.format(
                    system=system_id, path=file_path)
                # return HttpResponseRedirect(fm.download(system_id, file_path))
                resp = HttpResponseRedirect(url)
                resp['X-Authorization'] = 'Bearer {token}'.format(
                    token=request.user.agave_oauth.access_token)
                logger.info(resp)
                return resp

        return HttpResponseBadRequest("Unsupported operation")
Esempio n. 18
0
File: tasks.py Progetto: ziap/tgboj
def task_status_ajax(request):
    if 'id' not in request.GET:
        return HttpResponseBadRequest('Need to pass GET parameter "id"', content_type='text/plain')
    return JsonResponse(get_task_status(request.GET['id']))
Esempio n. 19
0
def update_translation(request):
    """Update entity translation for the specified locale and user."""

    try:
        entity = request.POST['entity']
        string = request.POST['translation']
        locale = request.POST['locale']
        plural_form = request.POST['plural_form']
        original = request.POST['original']
        ignore_warnings = request.POST.get('ignore_warnings',
                                           'false') == 'true'
        approve = request.POST.get('approve', 'false') == 'true'
        force_suggestions = request.POST.get('force_suggestions',
                                             'false') == 'true'
        paths = request.POST.getlist('paths[]')
    except MultiValueDictKeyError as e:
        return HttpResponseBadRequest('Bad Request: {error}'.format(error=e))

    try:
        e = Entity.objects.get(pk=entity)
    except Entity.DoesNotExist as error:
        log.error(str(error))
        return HttpResponse("error")

    try:
        locale = Locale.objects.get(code=locale)
    except Locale.DoesNotExist as error:
        log.error(str(error))
        return HttpResponse("error")

    if plural_form == "-1":
        plural_form = None

    user = request.user
    project = e.resource.project

    # Read-only translations cannot saved
    if utils.readonly_exists(project, locale):
        return HttpResponseForbidden(
            "Forbidden: This string is in read-only mode")

    try:
        use_ttk_checks = UserProfile.objects.get(user=user).quality_checks
    except UserProfile.DoesNotExist as error:
        use_ttk_checks = True

    # Disable checks for tutorial project.
    if project.slug == 'tutorial':
        use_ttk_checks = False

    now = timezone.now()
    can_translate = (request.user.can_translate(project=project, locale=locale)
                     and (not force_suggestions or approve))
    translations = Translation.objects.filter(entity=e,
                                              locale=locale,
                                              plural_form=plural_form)

    same_translations = translations.filter(string=string).order_by(
        '-active', 'rejected', '-date')

    # If same translation exists in the DB, don't save it again.
    if utils.is_same(same_translations, can_translate):
        return JsonResponse({
            'same': True,
        })

    failed_checks = run_checks(
        e,
        locale.code,
        original,
        string,
        use_ttk_checks,
    )

    if are_blocking_checks(failed_checks, ignore_warnings):
        return JsonResponse({
            'failedChecks': failed_checks,
        })

    # Translations exist
    if len(translations) > 0:
        # Same translation exists
        if len(same_translations) > 0:
            t = same_translations[0]

            # If added by privileged user, approve and unfuzzy it
            if can_translate and (t.fuzzy or not t.approved):
                if not t.active:
                    translations.filter(active=True).update(active=False)
                    t.active = True

                t.approved = True
                t.fuzzy = False
                t.rejected = False
                t.rejected_user = None
                t.rejected_date = None

                if t.approved_user is None:
                    t.approved_user = user
                    t.approved_date = now

                t.save()

                t.warnings.all().delete()
                t.errors.all().delete()
                save_failed_checks(t, failed_checks)

                return JsonResponse({
                    'type':
                    'updated',
                    'translation':
                    t.serialize(),
                    'stats':
                    TranslatedResource.objects.stats(project, paths, locale),
                })

        # Different translation added
        else:
            t = Translation(
                entity=e,
                locale=locale,
                plural_form=plural_form,
                string=string,
                user=user,
                date=now,
                approved=can_translate,
            )

            if can_translate:
                t.approved_user = user
                t.approved_date = now

            t.save()
            save_failed_checks(t, failed_checks)

            active_translation = e.reset_active_translation(
                locale=locale,
                plural_form=plural_form,
            )

            return JsonResponse({
                'type':
                'added',
                'translation':
                active_translation.serialize(),
                'stats':
                TranslatedResource.objects.stats(project, paths, locale),
            })

    # No translations saved yet
    else:
        t = Translation(
            entity=e,
            locale=locale,
            plural_form=plural_form,
            string=string,
            user=user,
            date=now,
            active=True,
            approved=can_translate,
        )

        if can_translate:
            t.approved_user = user
            t.approved_date = now

        t.save()
        save_failed_checks(t, failed_checks)

        return JsonResponse({
            'type':
            'saved',
            'translation':
            t.serialize(),
            'stats':
            TranslatedResource.objects.stats(project, paths, locale),
        })
Esempio n. 20
0
def add_pushover(request):
    if settings.PUSHOVER_API_TOKEN is None or settings.PUSHOVER_SUBSCRIPTION_URL is None:
        raise Http404("pushover integration is not available")

    if request.method == "POST":
        # Initiate the subscription
        nonce = get_random_string()
        request.session["po_nonce"] = nonce

        failure_url = settings.SITE_ROOT + reverse("hc-channels")
        success_url = settings.SITE_ROOT + reverse(
            "hc-add-pushover") + "?" + urlencode(
                {
                    "nonce": nonce,
                    "prio": request.POST.get("po_priority", "0"),
                })
        subscription_url = settings.PUSHOVER_SUBSCRIPTION_URL + "?" + urlencode(
            {
                "success": success_url,
                "failure": failure_url,
            })

        return redirect(subscription_url)

    # Handle successful subscriptions
    if "pushover_user_key" in request.GET:
        if "nonce" not in request.GET or "prio" not in request.GET:
            return HttpResponseBadRequest()

        # Validate nonce
        if request.GET["nonce"] != request.session.get("po_nonce"):
            return HttpResponseForbidden()

        # Validate priority
        if request.GET["prio"] not in ("-2", "-1", "0", "1", "2"):
            return HttpResponseBadRequest()

        # All looks well--
        del request.session["po_nonce"]

        if request.GET.get("pushover_unsubscribed") == "1":
            # Unsubscription: delete all Pushover channels for this user
            Channel.objects.filter(user=request.user, kind="po").delete()
            return redirect("hc-channels")
        else:
            # Subscription
            user_key = request.GET["pushover_user_key"]
            priority = int(request.GET["prio"])

            channel = Channel(user=request.team.user, kind="po")
            channel.value = "%s|%d" % (user_key, priority)
            channel.save()
            channel.assign_all_checks()
            return redirect("hc-channels")

    # Show Integration Settings form
    ctx = {
        "page": "channels",
        "po_retry_delay": td(seconds=settings.PUSHOVER_EMERGENCY_RETRY_DELAY),
        "po_expiration": td(seconds=settings.PUSHOVER_EMERGENCY_EXPIRATION),
    }
    return render(request, "integrations/add_pushover.html", ctx)
Esempio n. 21
0
def upload(request, album_id=0):

    id = int(album_id)
    upload_sessionid = request.COOKIES['sessionid']
    gallerys = Gallery.objects.filter(user_id=request.user.id)

    has_gallery = gallerys.count() > 0
    if not has_gallery:
        return HttpResponseRedirect(reverse('7create_album'))

    if request.method != 'POST':
        response = render_to_response('albums/upload.html',
                                      RequestContext(request, locals()))
        response.set_cookie('upload_sessionid',
                            upload_sessionid,
                            httponly=False)
        return response

    if request.FILES == None:
        return HttpResponseBadRequest('Must have files attached!')
    if 'selected_album' not in request.POST:
        return HttpResponseBadRequest('Must select a album')

    ufile = request.FILES[u'Filedata']
    id = int(request.POST['selected_album'])

    parent = str(id / 10000)
    child = str(id % 10000)

    print 'in  upload :' + ufile.name

    path = parent + '/' + child + '/'
    fold = os.path.join(MEDIA_ROOT, path)
    filename = str(random.randint(1, 1000)) + '_' + ufile.name
    filepath = path + filename
    thumbpath = filepath + '.thumbnail'
    thumbpath2 = thumbpath + '2'
    squarepath = filepath + '.square'

    if not os.path.exists(fold):
        os.makedirs(fold)

    print 'in uplaod :' + path

    image = Image.open(ufile)
    print image.info, filepath
    image.save(os.path.join(MEDIA_ROOT, filepath))
    print 'first save'
    image_square = image.resize((100, 100), Image.ANTIALIAS)
    image_square.save(os.path.join(MEDIA_ROOT, squarepath), 'JPEG')
    image.thumbnail((128, 128), Image.ANTIALIAS)
    image.save(os.path.join(MEDIA_ROOT, thumbpath), 'JPEG')
    image.thumbnail((64, 64), Image.ANTIALIAS)
    image.save(os.path.join(MEDIA_ROOT, thumbpath2), 'JPEG')

    gallery = Gallery.objects.select_for_update().get(id=id)
    gallery.photo_num = F('photo_num') + 1
    gallery.save()

    gallery = Gallery.objects.get(pk=gallery.pk)

    index = gallery.photo_num
    print 'index:', gallery.photo_num
    photo = Photo.objects.create(gallery_id=id,
                                 index=index,
                                 uname=ufile.name,
                                 name=filename,
                                 path=filepath,
                                 thumb128=thumbpath,
                                 thumb64=thumbpath2,
                                 square=squarepath)

    print 'after:', gallery.photo_num
    user_modify_gallery.send(sender=Photo, gallery=gallery)

    if not gallery.cover:
        gallery.cover = squarepath
        gallery.save()

    # update photo broadcast
    b_photos = B_Photo.objects.filter(gallery_id=id).order_by('-pub_date')
    if b_photos.count() != 0 and b_photos[0].pub_date.strftime(
            "%Y%m%d") == timezone.now().strftime("%Y%m%d"):
        b_photo = b_photos[0]
    else:
        b_photo = B_Photo.objects.create(user_id=request.user.id,
                                         gallery_id=id)

    b_photo.num = F('num') + 1
    b_photo.pub_date = timezone.now()
    b_photo.save()

    from django.utils import simplejson
    data = {'thumb64': photo.thumb64, 'index': photo.index}
    return HttpResponse(simplejson.dumps(data))
Esempio n. 22
0
    def _upload_file(self, request):
        """
        Upload file to the server.
        """
        if request.method == "POST":
            folder = request.GET.get('folder', '')

            if len(request.FILES) == 0:
                return HttpResponseBadRequest(
                    'Invalid request! No files included.')
            if len(request.FILES) > 1:
                return HttpResponseBadRequest(
                    'Invalid request! Multiple files included.')

            filedata = list(request.FILES.values())[0]

            fb_uploadurl_re = re.compile(
                r'^.*(%s)' %
                reverse("filebrowser:fb_upload", current_app=self.name))
            folder = fb_uploadurl_re.sub('', folder)

            path = os.path.join(self.directory, folder)
            # we convert the filename before uploading in order
            # to check for existing files/folders
            file_name = convert_filename(filedata.name)
            filedata.name = file_name
            file_path = os.path.join(path, file_name)
            file_already_exists = self.storage.exists(file_path)

            # Check for name collision with a directory
            if file_already_exists and self.storage.isdir(file_path):
                ret_json = {'success': False, 'filename': file_name}
                return HttpResponse(json.dumps(ret_json))

            signals.filebrowser_pre_upload.send(sender=request,
                                                path=folder,
                                                file=filedata,
                                                site=self)
            uploadedfile = handle_file_upload(path, filedata, site=self)

            if file_already_exists and OVERWRITE_EXISTING:
                old_file = smart_text(file_path)
                new_file = smart_text(uploadedfile)
                self.storage.move(new_file, old_file, allow_overwrite=True)
                full_path = FileObject(smart_text(old_file),
                                       site=self).path_full
            else:
                file_name = smart_text(uploadedfile)
                filedata.name = os.path.relpath(file_name, path)
                full_path = FileObject(smart_text(file_name),
                                       site=self).path_full

            # set permissions
            if DEFAULT_PERMISSIONS is not None:
                os.chmod(full_path, DEFAULT_PERMISSIONS)

            f = FileObject(smart_text(file_name), site=self)
            signals.filebrowser_post_upload.send(sender=request,
                                                 path=folder,
                                                 file=f,
                                                 site=self)

            # let Ajax Upload know whether we saved it or not
            ret_json = {'success': True, 'filename': f.filename}
            return HttpResponse(json.dumps(ret_json))
Esempio n. 23
0
def aggiungiRisposta(request, pk):
    sezione = get_object_or_404(Sezione, pk=pk)

    listUsrDR = UserDataReccomandation.objects.filter(user=request.user)
    if not (listUsrDR.count() > 0):
        usrDR = UserDataReccomandation.objects.create(hotel=0,
                                                      ristorante=0,
                                                      fastFood=0,
                                                      casaVacanza=0,
                                                      agriturismo=0,
                                                      user=request.user)
    else:
        usrDR = get_object_or_404(UserDataReccomandation, user=request.user)

    if (request.method == "POST"):
        form = PostModelForm(request.POST)
        if (form.is_valid()):
            form.save(commit=False)
            form.instance.sezione = sezione
            form.instance.autore_post = request.user
            form.save()
            url_discussione = reverse("sezione_view", kwargs={"pk": pk})

            user = get_object_or_404(User, pk=sezione.user.pk)
            if (user.first_name == ""):
                numero = 0
            else:
                numero = int(user.first_name)
            numero += 1
            user.first_name = str(numero)

            if (user.last_name == ""):
                notifiche = [{
                    "user_post": request.user.username,
                    "sezione_commentata": sezione.nome_sezione,
                    "sezione_url": url_discussione
                }]
                user.last_name = json.dumps(notifiche)
            else:
                temp = json.loads(user.last_name)
                temp.append({
                    "user_post": request.user.username,
                    "sezione_commentata": sezione.nome_sezione,
                    "sezione_url": url_discussione
                })
                user.last_name = json.dumps(temp)

            if (sezione.hotelB):
                usrDR.hotel += form.instance.rating
            if (sezione.ristoranteB):
                usrDR.ristorante += form.instance.rating
            if (sezione.fastFoodB):
                usrDR.fastFood += form.instance.rating
            if (sezione.casaVacanzaB):
                usrDR.casaVacanza += form.instance.rating
            if (sezione.agriturismoB):
                usrDR.agriturismo += form.instance.rating

            usrDR.save()
            user.save()

            print("numero di notifiche tot: " + user.first_name)
            print("lista urls: " + user.last_name)

            return HttpResponseRedirect(url_discussione)
    else:
        return HttpResponseBadRequest()
Esempio n. 24
0
    def post(self, request, file_mgr_name, system_id, file_path):
        if file_mgr_name == AgaveFileManager.NAME \
            or file_mgr_name == 'public':
            if not request.user.is_authenticated:
                return HttpResponseForbidden('Login required')

            agave_client = request.user.agave_oauth.client
            fm = AgaveFileManager(agave_client=agave_client)
            if request.FILES:
                upload_file = request.FILES['file']
                upload_dir = file_path

                relative_path = request.POST.get('relative_path', None)
                if relative_path:
                    # user uploaded a folder structure; ensure path exists
                    upload_dir = os.path.join(file_path,
                                              os.path.dirname(relative_path))
                    BaseFileResource.ensure_path(agave_client, system_id,
                                                 upload_dir)
                    metrics.info('Data Depot',
                                 extra={
                                     'user':
                                     request.user.username,
                                     'sessionId':
                                     getattr(request.session, 'session_key',
                                             ''),
                                     'operation':
                                     'data_depot_folder_upload',
                                     'info': {
                                         'filePath':
                                         file_path,
                                         'relativePath':
                                         os.path.dirname(relative_path),
                                         'systemId':
                                         system_id,
                                         'uploadDir':
                                         upload_dir
                                     }
                                 })
                try:
                    result = fm.upload(system_id, upload_dir, upload_file)
                    metrics.info('Data Depot',
                                 extra={
                                     'user':
                                     request.user.username,
                                     'sessionId':
                                     getattr(request.session, 'session_key',
                                             ''),
                                     'operation':
                                     'data_depot_file_upload',
                                     'info': {
                                         'systemId': system_id,
                                         'uploadDir': upload_dir,
                                         'uploadFile': upload_file
                                     }
                                 })
                    result['system'] = result['systemId']
                    result_file = BaseFileResource(agave_client, **result)
                    event_data = {
                        Notification.EVENT_TYPE: 'data_depot',
                        Notification.OPERATION: 'data_depot_file_upload',
                        Notification.STATUS: Notification.SUCCESS,
                        Notification.USER: request.user.username,
                        Notification.MESSAGE: 'File Upload was successful.',
                        Notification.EXTRA: result_file.to_dict()
                    }
                    Notification.objects.create(**event_data)
                except HTTPError as e:
                    logger.error(e.response.text)
                    event_data = {
                        Notification.EVENT_TYPE: 'data_depot',
                        Notification.OPERATION: 'data_depot_file_upload',
                        Notification.STATUS: Notification.ERROR,
                        Notification.USER: request.user.username,
                        Notification.MESSAGE:
                        'There was an error uploading one or more file(s).',
                        Notification.EXTRA: {
                            'system': system_id,
                            'file_path': file_path
                        }
                    }
                    Notification.objects.create(**event_data)
                    return HttpResponseBadRequest(e.response.text)

            return JsonResponse({'status': 'ok'})

        return HttpResponseBadRequest("Unsupported operation")
Esempio n. 25
0
def update_translation(request):
    """Update entity translation for the specified locale and user."""

    try:
        entity = request.POST['entity']
        string = request.POST['translation']
        locale = request.POST['locale']
        plural_form = request.POST['plural_form']
        original = request.POST['original']
        ignore_check = request.POST['ignore_check']
        approve = request.POST.get('approve', 'false') == 'true'
        force_suggestions = request.POST.get('force_suggestions',
                                             'false') == 'true'
        paths = request.POST.getlist('paths[]')
    except MultiValueDictKeyError as e:
        return HttpResponseBadRequest('Bad Request: {error}'.format(error=e))

    try:
        e = Entity.objects.get(pk=entity)
    except Entity.DoesNotExist as error:
        log.error(str(error))
        return HttpResponse("error")

    try:
        l = Locale.objects.get(code=locale)
    except Locale.DoesNotExist as error:
        log.error(str(error))
        return HttpResponse("error")

    if plural_form == "-1":
        plural_form = None

    user = request.user
    project = e.resource.project

    try:
        quality_checks = UserProfile.objects.get(user=user).quality_checks
    except UserProfile.DoesNotExist as error:
        quality_checks = True

    ignore = False
    if ignore_check == 'true' or not quality_checks:
        ignore = True

    now = timezone.now()
    can_translate = (request.user.can_translate(project=project, locale=l)
                     and (not force_suggestions or approve))
    translations = Translation.objects.filter(entity=e,
                                              locale=l,
                                              plural_form=plural_form)

    # Newlines are not allowed in .lang files (bug 1190754)
    if e.resource.format == 'lang' and '\n' in string:
        return HttpResponse('Newline characters are not allowed.')

    # Translations exist
    if len(translations) > 0:

        # Same translation exists
        same_translations = translations.filter(string=string).order_by(
            '-approved', 'rejected', '-date')
        if len(same_translations) > 0:
            t = same_translations[0]

            # If added by privileged user, approve and unfuzzy it
            if can_translate:

                # Unless there's nothing to be changed
                if t.user is not None and t.approved and t.approved_user \
                        and t.approved_date and not t.fuzzy:
                    return JsonResponse({
                        'same':
                        True,
                        'message':
                        'Same translation already exists.',
                    })

                warnings = utils.quality_check(original, string, l, ignore)
                if warnings:
                    return warnings

                translations.update(
                    approved=False,
                    approved_user=None,
                    approved_date=None,
                    rejected=True,
                    rejected_user=request.user,
                    rejected_date=timezone.now(),
                    fuzzy=False,
                )

                if t.user is None:
                    t.user = user

                t.approved = True
                t.approved_date = timezone.now()
                t.fuzzy = False
                t.rejected = False
                t.rejected_user = None
                t.rejected_date = None

                if t.approved_user is None:
                    t.approved_user = user
                    t.approved_date = now

                t.save()

                return JsonResponse({
                    'type':
                    'updated',
                    'translation':
                    t.serialize(),
                    'stats':
                    TranslatedResource.objects.stats(project, paths, l),
                })

            # If added by non-privileged user, unfuzzy it
            else:
                if t.fuzzy:
                    warnings = utils.quality_check(original, string, l, ignore)
                    if warnings:
                        return warnings

                    if t.user is None:
                        t.user = user

                    t.approved = False
                    t.approved_user = None
                    t.approved_date = None
                    t.fuzzy = False

                    t.save()

                    return JsonResponse({
                        'type':
                        'updated',
                        'translation':
                        t.serialize(),
                        'stats':
                        TranslatedResource.objects.stats(project, paths, l),
                    })

                return JsonResponse({
                    'same':
                    True,
                    'message':
                    'Same translation already exists.',
                })

        # Different translation added
        else:
            warnings = utils.quality_check(original, string, l, ignore)
            if warnings:
                return warnings

            if can_translate:
                translations.update(approved=False,
                                    approved_user=None,
                                    approved_date=None)

            translations.update(fuzzy=False)

            t = Translation(entity=e,
                            locale=l,
                            user=user,
                            string=string,
                            plural_form=plural_form,
                            date=now,
                            approved=can_translate)

            if can_translate:
                t.approved_user = user
                t.approved_date = now

            t.save()

            # Return active (approved or latest) translation
            try:
                active = translations.filter(approved=True).latest("date")
            except Translation.DoesNotExist:
                active = translations.latest("date")

            return JsonResponse({
                'type':
                'added',
                'translation':
                active.serialize(),
                'stats':
                TranslatedResource.objects.stats(project, paths, l),
            })

    # No translations saved yet
    else:
        warnings = utils.quality_check(original, string, l, ignore)
        if warnings:
            return warnings

        t = Translation(entity=e,
                        locale=l,
                        user=user,
                        string=string,
                        plural_form=plural_form,
                        date=now,
                        approved=can_translate)

        if can_translate:
            t.approved_user = user
            t.approved_date = now

        t.save()

        return JsonResponse({
            'type':
            'saved',
            'translation':
            t.serialize(),
            'stats':
            TranslatedResource.objects.stats(project, paths, l),
        })
Esempio n. 26
0
    def put(self, request, file_mgr_name, system_id, file_path):
        if request.is_ajax():
            body = json.loads(request.body)
        else:
            body = request.POST.copy()
        action = body.get('action', '')
        if file_mgr_name == AgaveFileManager.NAME \
            or file_mgr_name == 'public' \
            or file_mgr_name == 'community' \
            or file_mgr_name == 'published':

            if not request.user.is_authenticated:
                if file_mgr_name in ['public', 'community', 'published']:
                    if action in ['mkdir', 'move', 'rename', 'trash']:
                        return HttpResponseBadRequest('Invalid Action')
                    ag = get_user_model().objects.get(
                        username='******').agave_oauth.client
                else:
                    return HttpResponseForbidden('Login required')
            else:
                ag = request.user.agave_oauth.client

            fm = AgaveFileManager(agave_client=ag)
            if action == 'copy':
                try:
                    event_data = {
                        Notification.EVENT_TYPE: 'data_depot',
                        Notification.OPERATION: 'data_depot_copy',
                        Notification.STATUS: Notification.SUCCESS,
                        Notification.USER: request.user.username,
                        Notification.MESSAGE: 'Data was copied.',
                    }
                    if body.get('system') is None:
                        external = body.get('resource')
                        if external not in ['box', 'dropbox', 'googledrive']:
                            return HttpResponseBadRequest(
                                "External resource not available.")
                        if external == 'googledrive':
                            dest_file_id = body.get('id')
                        else:
                            dest_file_id = body.get('path')
                        external_resource_upload.apply_async(kwargs={
                            'username':
                            request.user.username,
                            'dest_resource':
                            external,
                            'src_file_id':
                            os.path.join(system_id, file_path.strip('/')),
                            'dest_file_id':
                            dest_file_id
                        },
                                                             queue='files')
                        event_data[
                            Notification.
                            MESSAGE] = 'Data copy was scheduled. This may take a few minutes.'
                        event_data[Notification.EXTRA] = {
                            'resource':
                            external,
                            'dest_file_id':
                            body.get('path'),
                            'src_file_id':
                            os.path.join(system_id, file_path.strip('/'))
                        }
                    elif body.get('system') != system_id:
                        if body.get('ipynb'):
                            path = '/{}'.format(request.user.username)
                        else:
                            path = body.get('path')
                        copied = fm.import_data(body.get('system'), path,
                                                system_id, file_path)
                        metrics.info('Data Depot',
                                     extra={
                                         'user':
                                         request.user.username,
                                         'sessionId':
                                         getattr(request.session,
                                                 'session_key', ''),
                                         'operation':
                                         'data_depot_copy',
                                         'info': {
                                             'destSystemId':
                                             body.get('system'),
                                             'destFilePath': path,
                                             'fromSystemId': system_id,
                                             'fromFilePath': file_path
                                         }
                                     })
                        event_data[Notification.EXTRA] = copied.to_dict()
                    else:
                        copied = fm.copy(system_id, file_path,
                                         body.get('path'), body.get('name'))
                        metrics.info('Data Depot',
                                     extra={
                                         'user':
                                         request.user.username,
                                         'sessionId':
                                         getattr(request.session,
                                                 'session_key', ''),
                                         'operation':
                                         'data_depot_copy',
                                         'info': {
                                             'destSystemId': system_id,
                                             'destFilePath': file_path,
                                             'fromSystemId':
                                             body.get('system'),
                                             'fromFilePath': body.get('path')
                                         }
                                     })
                        event_data[Notification.EXTRA] = copied.to_dict()

                    notification = Notification.objects.create(**event_data)
                    notification.save()
                    return JsonResponse(copied,
                                        encoder=AgaveJSONEncoder,
                                        safe=False)
                except HTTPError as e:
                    logger.exception(e.response.text)
                    event_data = {
                        Notification.EVENT_TYPE: 'data_depot',
                        Notification.OPERATION: 'data_depot_copy',
                        Notification.STATUS: Notification.ERROR,
                        Notification.USER: request.user.username,
                        Notification.MESSAGE:
                        'There was an error copying data.',
                        Notification.EXTRA: {
                            'message': e.response.text
                        }
                    }
                    Notification.objects.create(**event_data)
                    return HttpResponseBadRequest(e.response.text)

            elif action == 'download':
                metrics.info('Data Depot',
                             extra={
                                 'user':
                                 request.user.username,
                                 'sessionId':
                                 getattr(request.session, 'session_key', ''),
                                 'operation':
                                 'agave_file_download',
                                 'info': {
                                     'systemId': system_id,
                                     'filePath': file_path
                                 }
                             })
                return JsonResponse(
                    {'href': fm.download(system_id, file_path)})

            elif action == 'mkdir':
                try:
                    dir_name = body.get('name')
                    new_dir = fm.mkdir(system_id, file_path, dir_name)
                    metrics.info('Data Depot',
                                 extra={
                                     'user':
                                     request.user.username,
                                     'sessionId':
                                     getattr(request.session, 'session_key',
                                             ''),
                                     'operation':
                                     'agave_file_mkdir',
                                     'info': {
                                         'systemId': system_id,
                                         'filePath': file_path,
                                         'dirName': dir_name
                                     }
                                 })
                    event_data = {
                        Notification.EVENT_TYPE: 'data_depot',
                        Notification.OPERATION: 'data_depot_mkdir',
                        Notification.STATUS: Notification.SUCCESS,
                        Notification.USER: request.user.username,
                        Notification.MESSAGE: 'Directory created.',
                        Notification.EXTRA: new_dir.to_dict()
                    }
                    Notification.objects.create(**event_data)
                    return JsonResponse(new_dir,
                                        encoder=AgaveJSONEncoder,
                                        safe=False)
                except HTTPError as e:
                    logger.exception(e.response.text)
                    event_data = {
                        Notification.EVENT_TYPE: 'data_depot',
                        Notification.OPERATION: 'data_depot_mkdir',
                        Notification.STATUS: Notification.ERROR,
                        Notification.USER: request.user.username,
                        Notification.MESSAGE: 'Error creating directory.',
                        Notification.EXTRA: {
                            'message': e.response.text
                        }
                    }
                    Notification.objects.create(**event_data)
                    return HttpResponseBadRequest(e.response.text)

            elif action == 'move':
                try:
                    if body.get('system') != system_id:
                        moved = fm.import_data(body.get('system'),
                                               body.get('path'), system_id,
                                               file_path)
                        fm.delete(system_id, file_path)
                        metrics.info('Data Depot',
                                     extra={
                                         'user':
                                         request.user.username,
                                         'sessionId':
                                         getattr(request.session,
                                                 'session_key', ''),
                                         'operation':
                                         'agave_file_copy_move',
                                         'info': {
                                             'destSystemId':
                                             body.get('system'),
                                             'destFilePath': body.get('path'),
                                             'fromSystemId': system_id,
                                             'fromFilePath': file_path
                                         }
                                     })
                    else:
                        moved = fm.move(system_id, file_path, body.get('path'),
                                        body.get('name'))
                        metrics.info('Data Depot',
                                     extra={
                                         'user':
                                         request.user.username,
                                         'sessionId':
                                         getattr(request.session,
                                                 'session_key', ''),
                                         'operation':
                                         'agave_file_copy',
                                         'info': {
                                             'destSystemId': system_id,
                                             'destFilePath': file_path,
                                             'fromSystemId':
                                             body.get('system'),
                                             'fromFilePath': body.get('path')
                                         }
                                     })
                    event_data = {
                        Notification.EVENT_TYPE: 'data_depot',
                        Notification.STATUS: Notification.SUCCESS,
                        Notification.OPERATION: 'data_depot_move',
                        Notification.USER: request.user.username,
                        Notification.MESSAGE: 'Data has been moved.',
                        Notification.EXTRA: moved.to_dict()
                    }
                    Notification.objects.create(**event_data)
                    return JsonResponse(moved,
                                        encoder=AgaveJSONEncoder,
                                        safe=False)
                except HTTPError as e:
                    logger.exception(e.response.text)
                    event_data = {
                        Notification.EVENT_TYPE: 'data_depot_move',
                        Notification.STATUS: Notification.ERROR,
                        Notification.OPERATION: 'data_depot_move',
                        Notification.USER: request.user.username,
                        Notification.MESSAGE:
                        'There was an error moving your data.',
                        Notification.EXTRA: {
                            'message': e.response.text
                        }
                    }
                    Notification.objects.create(**event_data)
                    return HttpResponseBadRequest(e.response.text)

            elif action == 'preview':
                try:
                    file_listing = fm.listing(system_id, file_path)
                    if file_listing.previewable:
                        preview_url = reverse(
                            'designsafe_api:files_media',
                            args=[file_mgr_name, system_id, file_path])
                        return JsonResponse({
                            'href':
                            '{}?preview=true'.format(preview_url),
                            'postit':
                            file_listing.download_postit(force=False,
                                                         lifetime=360)
                        })
                    else:
                        return HttpResponseBadRequest(
                            'Preview not available for this item.')
                except HTTPError as e:
                    logger.exception(
                        'Unable to preview file: {file_path}'.format(
                            file_path=file))
                    return HttpResponseBadRequest(e.response.text)

            elif action == 'rename':
                try:
                    renamed = fm.rename(system_id, file_path, body.get('name'))
                    metrics.info('Data Depot',
                                 extra={
                                     'user':
                                     request.user.username,
                                     'sessionId':
                                     getattr(request.session, 'session_key',
                                             ''),
                                     'operation':
                                     'agave_file_rename',
                                     'info': {
                                         'systemId': system_id,
                                         'filePath': file_path,
                                         'name': body.get('name')
                                     }
                                 })
                    event_data = {
                        Notification.EVENT_TYPE: 'data_depot_rename',
                        Notification.STATUS: Notification.SUCCESS,
                        Notification.USER: request.user.username,
                        Notification.MESSAGE: 'File/folder was renamed.',
                        Notification.EXTRA: renamed.to_dict()
                    }
                    Notification.objects.create(**event_data)
                    return JsonResponse(renamed,
                                        encoder=AgaveJSONEncoder,
                                        safe=False)
                except HTTPError as e:
                    logger.exception(e.response.text)
                    event_data = {
                        Notification.EVENT_TYPE: 'data_depot_rename',
                        Notification.STATUS: Notification.ERROR,
                        Notification.USER: request.user.username,
                        Notification.MESSAGE:
                        'There was an error renaming a file/folder.',
                        Notification.EXTRA: {
                            'message': e.response.text
                        }
                    }
                    Notification.objects.create(**event_data)
                    return HttpResponseBadRequest(e.response.text)

            elif action == 'trash':
                trash_path = '/Trash'
                if system_id == AgaveFileManager.DEFAULT_SYSTEM_ID:
                    trash_path = request.user.username + '/.Trash'

                try:
                    trashed = fm.trash(system_id, file_path, trash_path)
                    metrics.info('Data Depot',
                                 extra={
                                     'user':
                                     request.user.username,
                                     'sessionId':
                                     getattr(request.session, 'session_key',
                                             ''),
                                     'operation':
                                     'agave_file_trash',
                                     'info': {
                                         'systemId': system_id,
                                         'filePath': file_path,
                                         'trashPath': trash_path
                                     }
                                 })
                    event_data = {
                        Notification.EVENT_TYPE: 'data_depot',
                        Notification.STATUS: Notification.SUCCESS,
                        Notification.OPERATION: 'data_depot_trash',
                        Notification.USER: request.user.username,
                        Notification.MESSAGE:
                        'File/folder was moved to trash.',
                        Notification.EXTRA: trashed.to_dict()
                    }
                    Notification.objects.create(**event_data)
                    return JsonResponse(trashed,
                                        encoder=AgaveJSONEncoder,
                                        safe=False)
                except HTTPError as e:
                    logger.error(e.response.text)
                    event_data = {
                        Notification.EVENT_TYPE: 'data_depot_trash',
                        Notification.STATUS: Notification.ERROR,
                        Notification.OPERATION: 'data_depot_trash',
                        Notification.USER: request.user.username,
                        Notification.MESSAGE:
                        'There was an error moving file/folder to trash.',
                        Notification.EXTRA: {
                            'message': e.response.text
                        }
                    }
                    Notification.objects.create(**event_data)
                    return HttpResponseBadRequest(e.response.text)

        return HttpResponseBadRequest("Unsupported operation")
Esempio n. 27
0
def vcs_service_hook(request, service):
    """Shared code between VCS service hooks.

    Currently used for bitbucket_hook, github_hook and gitlab_hook, but should
    be usable for other VCS services (Google Code, custom coded sites, etc.)
    too.
    """
    # We support only post methods
    if not settings.ENABLE_HOOKS:
        return HttpResponseNotAllowed(())

    # Check if we got payload
    try:
        data = parse_hook_payload(request)
    except (ValueError, KeyError, UnicodeError):
        return HttpResponseBadRequest('Could not parse JSON payload!')

    # Get service helper
    hook_helper = HOOK_HANDLERS[service]

    # Send the request data to the service handler.
    try:
        service_data = hook_helper(data)
    except Exception as error:
        LOGGER.error('failed to parse service %s data', service)
        report_error(error, sys.exc_info())
        return HttpResponseBadRequest('Invalid data in json payload!')

    # Log data
    service_long_name = service_data['service_long_name']
    repos = service_data['repos']
    repo_url = service_data['repo_url']
    branch = service_data['branch']

    # Generate filter
    spfilter = Q(repo__in=repos)

    # We need to match also URLs which include username and password
    for repo in repos:
        if not repo.startswith('https://'):
            continue
        spfilter = spfilter | (Q(repo__startswith='https://')
                               & Q(repo__endswith='@{0}'.format(repo[8:])))

    all_components = Component.objects.filter(spfilter)

    if branch is not None:
        all_components = all_components.filter(branch=branch)

    components = all_components.filter(project__enable_hooks=True)

    LOGGER.info(
        'received %s notification on repository %s, branch %s,'
        '%d matching components, %d to process',
        service_long_name,
        repo_url,
        branch,
        all_components.count(),
        components.count(),
    )

    # Trigger updates
    updates = 0
    for obj in components:
        updates += 1
        LOGGER.info('%s notification will update %s', service_long_name, obj)
        perform_update(obj)

    if updates == 0:
        return hook_response('No matching repositories found!', 'failure')

    return hook_response()
Esempio n. 28
0
    def post(self, request, file_mgr_name, system_id, file_path):
        if request.is_ajax():
            body = json.loads(request.body)
        else:
            body = request.POST.copy()

        if file_mgr_name == AgaveFileManager.NAME \
            or file_mgr_name == 'public':
            if not request.user.is_authenticated:
                return HttpResponseForbidden('Login required')

            fm = AgaveFileManager(agave_client=request.user.agave_oauth.client)
            username = body.get('username')
            permission = body.get('permission')
            try:
                pem = fm.share(system_id, file_path, username, permission)
                metrics.info('Data Depot',
                             extra={
                                 'user':
                                 request.user.username,
                                 'sessionId':
                                 getattr(request.session, 'session_key', ''),
                                 'operation':
                                 'data_depot_share',
                                 'info': {
                                     'systemId': system_id,
                                     'filePath': file_path
                                 }
                             })
                event_data = {
                    Notification.EVENT_TYPE:
                    'data_depot',
                    Notification.OPERATION:
                    'data_depot_share',
                    Notification.STATUS:
                    Notification.SUCCESS,
                    Notification.USER:
                    request.user.username,
                    Notification.MESSAGE:
                    '{} permissions were granted to {}.'.format(
                        permission, username),
                    Notification.EXTRA: {
                        'system': system_id,
                        'file_path': file_path,
                        'username': username,
                        'permission': permission
                    }
                }
                Notification.objects.create(**event_data)
            except HTTPError as err:
                logger.debug(err.response.text)
                event_data = {
                    Notification.EVENT_TYPE: 'data_depot_share',
                    Notification.STATUS: Notification.ERROR,
                    Notification.OPERATION: 'data_depot_share',
                    Notification.USER: request.user.username,
                    Notification.MESSAGE:
                    'There was an error updating permissions for a file/folder.',
                    Notification.EXTRA: {
                        'message': err.response.text
                    }
                }
                Notification.objects.create(**event_data)
                return HttpResponseBadRequest(err.response.text)
            return JsonResponse(pem, encoder=AgaveJSONEncoder, safe=False)

        return HttpResponseBadRequest("Unsupported operation")
Esempio n. 29
0
 def _wrapped_view(request, *args, **kwargs):
     if request.is_ajax():
         return view_func(request, *args, **kwargs)
     else:
         return HttpResponseBadRequest()
Esempio n. 30
0
 def new_application(request, software_license):
     return HttpResponseBadRequest("<h1>Restricted Software denied.</h1>")