def test_set_project_perms_to_xform_async(self, mock):
     """
     Test that the set_project_perms_to_xform_async task actually calls
     the set_project_perms_to_xform function
     """
     self._publish_transportation_form()
     set_project_perms_to_xform_async.delay(self.xform.pk, self.project.pk)
     self.assertTrue(mock.called)
     args, _kwargs = mock.call_args_list[0]
     self.assertEqual(args[0], self.xform)
     self.assertEqual(args[1], self.project)
Exemple #2
0
def publish_project_xform(request, project):
    def set_form():
        props = {
            'project': project.pk,
            'dropbox_xls_url': request.data.get('dropbox_xls_url'),
            'xls_url': request.data.get('xls_url'),
            'csv_url': request.data.get('csv_url'),
            'text_xls_form': request.data.get('text_xls_form')
        }

        form = QuickConverter(props, request.FILES)

        return form.publish(project.organization, created_by=request.user)

    xform = None

    def id_string_exists_in_account():
        try:
            XForm.objects.get(user=project.organization,
                              id_string=xform.id_string)
        except XForm.DoesNotExist:
            return False

        return True

    if 'formid' in request.data:
        xform = get_object_or_404(XForm, pk=request.data.get('formid'))
        safe_delete('{}{}'.format(PROJ_FORMS_CACHE, xform.project.pk))
        safe_delete('{}{}'.format(PROJ_BASE_FORMS_CACHE, xform.project.pk))
        if not ManagerRole.user_has_role(request.user, xform):
            raise exceptions.PermissionDenied(
                _("{} has no manager/owner role to the form {}".format(
                    request.user, xform)))

        msg = 'Form with the same id_string already exists in this account'
        # Without this check, a user can't transfer a form to projects that
        # he/she owns because `id_string_exists_in_account` will always
        # return true
        if project.organization != xform.user and \
                id_string_exists_in_account():
            raise exceptions.ParseError(_(msg))
        xform.user = project.organization
        xform.project = project

        try:
            with transaction.atomic():
                xform.save()
        except IntegrityError:
            raise exceptions.ParseError(_(msg))
        set_project_perms_to_xform_async.delay(xform.pk, project.pk)
    else:
        xform = publish_form(set_form)

    return xform
Exemple #3
0
 def test_set_project_perms_to_xform_async(self, mock):
     """
     Test that the set_project_perms_to_xform_async task actually calls
     the set_project_perms_to_xform function
     """
     self._publish_transportation_form()
     set_project_perms_to_xform_async.delay(self.xform.pk, self.project.pk)
     self.assertTrue(mock.called)
     args, _kwargs = mock.call_args_list[0]
     self.assertEqual(args[0], self.xform)
     self.assertEqual(args[1], self.project)
Exemple #4
0
def set_object_permissions(sender, instance=None, created=False, **kwargs):
    """
    Apply the relevant object permissions for the form to all users who should
    have access to it.
    """
    if instance.project:
        # clear cache
        safe_delete('{}{}'.format(PROJ_FORMS_CACHE, instance.project.pk))
        safe_delete('{}{}'.format(PROJ_BASE_FORMS_CACHE, instance.project.pk))

    # seems the super is not called, have to get xform from here
    xform = XForm.objects.get(pk=instance.pk)

    if created:
        from onadata.libs.permissions import OwnerRole

        OwnerRole.add(instance.user, xform)

        if instance.created_by and instance.user != instance.created_by:
            OwnerRole.add(instance.created_by, xform)

        from onadata.libs.utils.project_utils import set_project_perms_to_xform_async  # noqa
        try:
            set_project_perms_to_xform_async.delay(xform.pk,
                                                   instance.project.pk)
        except OperationalError:
            from onadata.libs.utils.project_utils import set_project_perms_to_xform  # noqa
            set_project_perms_to_xform(xform, instance.project)

    if hasattr(instance, 'has_external_choices') \
            and instance.has_external_choices:
        instance.xls.seek(0)
        f = sheet_to_csv(instance.xls.read(), 'external_choices')
        f.seek(0, os.SEEK_END)
        size = f.tell()
        f.seek(0)

        from onadata.apps.main.models.meta_data import MetaData
        data_file = InMemoryUploadedFile(
            file=f,
            field_name='data_file',
            name='itemsets.csv',
            content_type='text/csv',
            size=size,
            charset=None
        )

        MetaData.media_upload(xform, data_file)
def set_object_permissions(sender, instance=None, created=False, **kwargs):
    """
    Apply the relevant object permissions for the form to all users who should
    have access to it.
    """
    if instance.project:
        # clear cache
        safe_delete('{}{}'.format(PROJ_FORMS_CACHE, instance.project.pk))
        safe_delete('{}{}'.format(PROJ_BASE_FORMS_CACHE, instance.project.pk))

    # seems the super is not called, have to get xform from here
    xform = XForm.objects.get(pk=instance.pk)

    if created:
        from onadata.libs.permissions import OwnerRole

        OwnerRole.add(instance.user, xform)

        if instance.created_by and instance.user != instance.created_by:
            OwnerRole.add(instance.created_by, xform)

        from onadata.libs.utils.project_utils import set_project_perms_to_xform_async  # noqa
        try:
            set_project_perms_to_xform_async.delay(xform.pk,
                                                   instance.project.pk)
        except OperationalError:
            from onadata.libs.utils.project_utils import set_project_perms_to_xform  # noqa
            set_project_perms_to_xform(xform, instance.project)

    if hasattr(instance, 'has_external_choices') \
            and instance.has_external_choices:
        instance.xls.seek(0)
        f = sheet_to_csv(instance.xls.read(), 'external_choices')
        f.seek(0, os.SEEK_END)
        size = f.tell()
        f.seek(0)

        from onadata.apps.main.models.meta_data import MetaData
        data_file = InMemoryUploadedFile(
            file=f,
            field_name='data_file',
            name='itemsets.csv',
            content_type='text/csv',
            size=size,
            charset=None
        )

        MetaData.media_upload(xform, data_file)
Exemple #6
0
def publish_project_xform(request, project):
    """
    Publish XLSForm to a project given a request.
    """
    def set_form():
        """
        Instantiates QuickConverter form to publish a form.
        """
        props = {
            'project': project.pk,
            'dropbox_xls_url': request.data.get('dropbox_xls_url'),
            'xls_url': request.data.get('xls_url'),
            'csv_url': request.data.get('csv_url'),
            'text_xls_form': request.data.get('text_xls_form')
        }

        form = QuickConverter(props, request.FILES)

        return form.publish(project.organization, created_by=request.user)

    xform = None

    def id_string_exists_in_account():
        """
        Checks if an id_string exists in an account, returns True if it exists
        otherwise returns False.
        """
        try:
            XForm.objects.get(user=project.organization,
                              id_string=xform.id_string)
        except XForm.DoesNotExist:
            return False
        return True

    if 'formid' in request.data:
        xform = get_object_or_404(XForm, pk=request.data.get('formid'))
        safe_delete('{}{}'.format(PROJ_FORMS_CACHE, xform.project.pk))
        safe_delete('{}{}'.format(PROJ_BASE_FORMS_CACHE, xform.project.pk))
        if not ManagerRole.user_has_role(request.user, xform):
            raise exceptions.PermissionDenied(
                _("{} has no manager/owner role to the form {}".format(
                    request.user, xform)))

        msg = 'Form with the same id_string already exists in this account'
        # Without this check, a user can't transfer a form to projects that
        # he/she owns because `id_string_exists_in_account` will always
        # return true
        if project.organization != xform.user and \
                id_string_exists_in_account():
            raise exceptions.ParseError(_(msg))
        xform.user = project.organization
        xform.project = project

        try:
            with transaction.atomic():
                xform.save()
        except IntegrityError:
            raise exceptions.ParseError(_(msg))
        else:
            # First assign permissions to the person who uploaded the form
            OwnerRole.add(request.user, xform)
            try:
                # Next run async task to apply all other perms
                set_project_perms_to_xform_async.delay(xform.pk, project.pk)
            except OperationalError:
                # Apply permissions synchrounously
                set_project_perms_to_xform(xform, project)
    else:
        xform = publish_form(set_form)

    return xform
Exemple #7
0
def publish_project_xform(request, project):
    """
    Publish XLSForm to a project given a request.
    """

    def set_form():
        """
        Instantiates QuickConverter form to publish a form.
        """
        props = {
            'project': project.pk,
            'dropbox_xls_url': request.data.get('dropbox_xls_url'),
            'xls_url': request.data.get('xls_url'),
            'csv_url': request.data.get('csv_url'),
            'text_xls_form': request.data.get('text_xls_form')
        }

        form = QuickConverter(props, request.FILES)

        return form.publish(project.organization, created_by=request.user)

    xform = None

    def id_string_exists_in_account():
        """
        Checks if an id_string exists in an account, returns True if it exists
        otherwise returns False.
        """
        try:
            XForm.objects.get(
                user=project.organization, id_string=xform.id_string)
        except XForm.DoesNotExist:
            return False
        return True

    if 'formid' in request.data:
        xform = get_object_or_404(XForm, pk=request.data.get('formid'))
        safe_delete('{}{}'.format(PROJ_FORMS_CACHE, xform.project.pk))
        safe_delete('{}{}'.format(PROJ_BASE_FORMS_CACHE, xform.project.pk))
        if not ManagerRole.user_has_role(request.user, xform):
            raise exceptions.PermissionDenied(
                _("{} has no manager/owner role to the form {}".format(
                    request.user, xform)))

        msg = 'Form with the same id_string already exists in this account'
        # Without this check, a user can't transfer a form to projects that
        # he/she owns because `id_string_exists_in_account` will always
        # return true
        if project.organization != xform.user and \
                id_string_exists_in_account():
            raise exceptions.ParseError(_(msg))
        xform.user = project.organization
        xform.project = project

        try:
            with transaction.atomic():
                xform.save()
        except IntegrityError:
            raise exceptions.ParseError(_(msg))
        else:
            # First assign permissions to the person who uploaded the form
            OwnerRole.add(request.user, xform)
            try:
                # Next run async task to apply all other perms
                set_project_perms_to_xform_async.delay(xform.pk, project.pk)
            except OperationalError:
                # Apply permissions synchrounously
                set_project_perms_to_xform(xform, project)
    else:
        xform = publish_form(set_form)

    return xform