diff --git a/onadata/apps/api/permissions.py b/onadata/apps/api/permissions.py index 093e66d361..360cde8bd6 100644 --- a/onadata/apps/api/permissions.py +++ b/onadata/apps/api/permissions.py @@ -82,8 +82,8 @@ class ExportDjangoObjectPermission(AlternateHasObjectPermissionMixin, } def has_permission(self, request, view): - is_authenticated = (request and request.user - and request.user.is_authenticated()) + is_authenticated = (request and request.user and + request.user.is_authenticated()) if not is_authenticated: view._ignore_model_permissions = True # pylint: disable=W0212 diff --git a/onadata/apps/api/tests/viewsets/test_export_viewset.py b/onadata/apps/api/tests/viewsets/test_export_viewset.py index 638a4e75c1..b75a35a258 100644 --- a/onadata/apps/api/tests/viewsets/test_export_viewset.py +++ b/onadata/apps/api/tests/viewsets/test_export_viewset.py @@ -109,6 +109,29 @@ def test_export_list_public(self): self.assertTrue(bool(response.data)) self.assertEqual(status.HTTP_200_OK, response.status_code) + def test_export_list_public_form(self): + """ + Test ExportViewSet list endpoint for a single public form. + """ + user_mosh = self._create_user('mosh', 'mosh') + self._publish_transportation_form() + self.xform.shared_data = True + self.xform.save() + temp_dir = settings.MEDIA_ROOT + dummy_export_file = NamedTemporaryFile(suffix='.xlsx', dir=temp_dir) + filename = os.path.basename(dummy_export_file.name) + filedir = os.path.dirname(dummy_export_file.name) + export = Export.objects.create(xform=self.xform, + filename=filename, + filedir=filedir) + export.save() + view = ExportViewSet.as_view({'get': 'list'}) + request = self.factory.get('/export', {'xform': self.xform.pk}) + force_authenticate(request, user=user_mosh) + response = view(request) + self.assertTrue(bool(response.data)) + self.assertEqual(status.HTTP_200_OK, response.status_code) + def test_export_public_project(self): """ Test export of a public form for anonymous users. diff --git a/onadata/libs/filters.py b/onadata/libs/filters.py index cfe6048441..6d8aa90ce7 100644 --- a/onadata/libs/filters.py +++ b/onadata/libs/filters.py @@ -206,19 +206,24 @@ class XFormPermissionFilterMixin(object): def _xform_filter(self, request, view, keyword): """Use XForm permissions""" + xform = request.query_params.get('xform') + public_forms = XForm.objects.none() if xform: int_or_parse_error(xform, u"Invalid value for formid %s.") self.xform = get_object_or_404(XForm, pk=xform) xform_qs = XForm.objects.filter(pk=self.xform.pk) + public_forms = XForm.objects.filter(pk=self.xform.pk, + shared_data=True) else: xform_qs = XForm.objects.all() xform_qs = xform_qs.filter(deleted_at=None) + if request.user.is_anonymous(): xforms = xform_qs.filter(shared_data=True) else: xforms = super(XFormPermissionFilterMixin, self).filter_queryset( - request, xform_qs, view) + request, xform_qs, view) | public_forms return {"%s__in" % keyword: xforms} def _xform_filter_queryset(self, request, queryset, view, keyword):