def test_upload_source_file_keep_name(self): desc = "Snooky" response = self.client.post(self.edit_url, {"source": desc}, HTTP_X_REQUESTED_WITH="XMLHttpRequest") self.assertEqual(response.status_code, 200) name = self._add_metadata("source") self.assertNotEqual(MetaData.source(self.xform).data_file, None) self.assertEqual(MetaData.source(self.xform).data_value, desc)
def test_upload_source_file_keep_name(self): desc = 'Snooky' response = self.client.post(self.edit_url, {'source': desc}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 200) name = self._add_metadata('source') self.assertNotEqual(MetaData.source(self.xform).data_file, None) self.assertEqual(MetaData.source(self.xform).data_value, desc)
def test_user_add_crowdform_duplicate_entry(self): self._add_crowdform() self.assertEqual(self.response.status_code, 302) meta = MetaData.crowdform_users(self.xform) self.assertEqual(len(meta), 1) self._add_crowdform() meta = MetaData.crowdform_users(self.xform) self.assertEqual(len(meta), 1)
def test_private_set_link_to_share_toggle_off(self): response = self.client.post(self.perm_url, {"for_user": "******", "perm_type": "link"}) self.assertEqual(MetaData.public_link(self.xform), True) response = self.anon.get(self.show_url) self.assertEqual(response.status_code, 302) self.assertEqual(response["Location"], "%s%s" % (self.base_url, self.show_normal_url)) response = self.client.post(self.perm_url, {"for_user": "******", "perm_type": "link"}) self.assertEqual(MetaData.public_link(self.xform), False) response = self.anon.get(self.show_url) # follow redirect response = self.anon.get(response["Location"]) self.assertEqual(response.status_code, 302) self.assertNotEqual(response["Location"], "%s%s" % (self.base_url, self.show_normal_url))
def edit(request, username, id_string): xform = XForm.objects.get(user__username=username, id_string=id_string) if username == request.user.username or\ request.user.has_perm('odk_logger.change_xform', xform): if request.POST.get('description'): xform.description = request.POST['description'] elif request.POST.get('title'): xform.title = request.POST['title'] elif request.POST.get('toggle_shared'): if request.POST['toggle_shared'] == 'data': xform.shared_data = not xform.shared_data elif request.POST['toggle_shared'] == 'form': xform.shared = not xform.shared elif request.POST['toggle_shared'] == 'active': xform.downloadable = not xform.downloadable elif request.POST.get('form-license'): MetaData.form_license(xform, request.POST['form-license']) elif request.POST.get('data-license'): MetaData.data_license(xform, request.POST['data-license']) elif request.POST.get('source') or request.FILES.get('source'): MetaData.source(xform, request.POST.get('source'), request.FILES.get('source')) elif request.FILES: MetaData.supporting_docs(xform, request.FILES['doc']) xform.update() if request.is_ajax(): return HttpResponse('Updated succeeded.') else: return HttpResponseRedirect(reverse(show, kwargs={ 'username': username, 'id_string': id_string })) return HttpResponseForbidden('Update failed.')
def map_view(request, username, id_string): owner = get_object_or_404(User, username=username) xform = get_object_or_404(XForm, id_string=id_string, user=owner) if not has_permission(xform, owner, request): return HttpResponseForbidden(_(u"Not shared.")) context = RequestContext(request) context.content_user = owner context.xform = xform context.profile, created = UserProfile.objects.get_or_create(user=owner) points = ParsedInstance.objects.values("lat", "lng", "instance").filter( instance__user=owner, instance__xform__id_string=id_string, lat__isnull=False, lng__isnull=False ) center = { "lat": round_down_geopoint(average([p["lat"] for p in points])), "lng": round_down_geopoint(average([p["lng"] for p in points])), } def round_down_point(p): return {"lat": round_down_geopoint(p["lat"]), "lng": round_down_geopoint(p["lng"]), "instance": p["instance"]} context.center = json.dumps(center) context.form_view = True context.jsonform_url = reverse(download_jsonform, kwargs={"username": username, "id_string": id_string}) context.mongo_api_url = reverse(main.views.api, kwargs={"username": username, "id_string": id_string}) context.mapbox_layer = MetaData.mapbox_layer_upload(xform) return render_to_response("map.html", context_instance=context)
def test_public_with_link_to_share(self): response = self.client.post(self.perm_url, {"for_user": "******", "perm_type": "link"}) self.assertEqual(response.status_code, 302) self.assertEqual(MetaData.public_link(self.xform), True) response = self.anon.get(self.show_url) self.assertEqual(response.status_code, 302) self.assertEqual(response["Location"], "%s%s" % (self.base_url, self.show_normal_url))
def auto_add_crowd_form_to_registered_user(sender, **kwargs): new_user = kwargs.get('user') if hasattr(settings, 'AUTO_ADD_CROWDFORM') and \ settings.AUTO_ADD_CROWDFORM and \ hasattr(settings, 'DEFAULT_CROWDFORM'): try: default_crowdform = settings.DEFAULT_CROWDFORM if isinstance(default_crowdform, dict) and\ 'xform_username' in default_crowdform and\ 'xform_id_string' in default_crowdform: xform = XForm.objects.get( id_string=default_crowdform['xform_id_string'], user__username=default_crowdform['xform_username']) MetaData.crowdform_users(xform, new_user.username) except XForm.DoesNotExist: pass
def formList(request, username): render_formlist = False formlist_user = get_object_or_404(User, username=username) profile, created = UserProfile.objects.get_or_create(user=formlist_user) if profile.require_auth: # source, http://djangosnippets.org/snippets/243/ if 'HTTP_AUTHORIZATION' in request.META: auth = request.META['HTTP_AUTHORIZATION'].split() # NOTE: We are only support BASIC authentication for now. if len(auth) == 2 and auth[0].lower() == "basic": uname, passwd = base64.b64decode(auth[1]).split(':') # ensure listing this user's forms if formlist_user.username == uname: user = authenticate(username=uname, password=passwd) if user is not None and user.is_active: render_formlist = True else: render_formlist = True if render_formlist: """This is where ODK Collect gets its download list.""" xforms = XForm.objects.filter(downloadable=True, user__username=username) urls = [ {'url': request.build_absolute_uri(xform.url()), 'text': xform.title , 'media': {'m': MetaData.media_upload(xform), 'user': xform.user, 'id': xform.id_string}} for xform in xforms ] return render_to_response("formList.xml", {'urls': urls, 'host': 'http://%s' % request.get_host()}, mimetype="text/xml") return HttpResponseNotAuthorized('Must be logged in')
def xformsManifest(request, username, id_string): xform = get_object_or_404(XForm, id_string=id_string, user__username=username) formlist_user = xform.user profile, created = \ UserProfile.objects.get_or_create(user=formlist_user) if profile.require_auth: authenticator = HttpDigestAuthenticator() if not authenticator.authenticate(request): return authenticator.build_challenge_response() response = render_to_response( "xformsManifest.xml", { #'urls': urls, 'host': request.build_absolute_uri().replace(request.get_full_path(), ''), 'media_files': MetaData.media_upload(xform) }, mimetype="text/xml; charset=utf-8") response['X-OpenRosa-Version'] = '1.0' tz = pytz.timezone(settings.TIME_ZONE) dt = datetime.now(tz).strftime('%a, %d %b %Y %H:%M:%S %Z') response['Date'] = dt return response
def map_view(request, username, id_string): owner = get_object_or_404(User, username=username) xform = get_object_or_404(XForm, id_string=id_string, user=owner) if not has_permission(xform, owner, request): return HttpResponseForbidden('Not shared.') context = RequestContext(request) context.content_user = owner context.xform = xform context.profile, created = UserProfile.objects.get_or_create(user=owner) points = ParsedInstance.objects.values('lat', 'lng', 'instance').filter( instance__user=owner, instance__xform__id_string=id_string, lat__isnull=False, lng__isnull=False) center = { 'lat': round_down_geopoint(average([p['lat'] for p in points])), 'lng': round_down_geopoint(average([p['lng'] for p in points])), } def round_down_point(p): return { 'lat': round_down_geopoint(p['lat']), 'lng': round_down_geopoint(p['lng']), 'instance': p['instance'] } context.center = json.dumps(center) context.form_view = True context.jsonform_url = reverse(download_jsonform, \ kwargs={"username": username, "id_string":id_string}) context.mongo_api_url = reverse(main.views.api, \ kwargs={"username": username, "id_string": id_string}) context.mapbox_layer = MetaData.mapbox_layer_upload(xform) return render_to_response('map.html', context_instance=context)
def show(request, username=None, id_string=None, uuid=None): if uuid: xform = get_object_or_404(XForm, uuid=uuid) request.session["public_link"] = xform.uuid if MetaData.public_link(xform) else False return HttpResponseRedirect( reverse(show, kwargs={"username": xform.user.username, "id_string": xform.id_string}) ) xform, is_owner, can_edit, can_view = get_xform_and_perms(username, id_string, request) # no access if not (xform.shared or can_view or request.session.get("public_link")): return HttpResponseRedirect(reverse(home)) context = RequestContext(request) context.cloned = ( len(XForm.objects.filter(user__username=request.user.username, id_string=id_string + XForm.CLONED_SUFFIX)) > 0 ) context.public_link = MetaData.public_link(xform) context.is_owner = is_owner context.can_edit = can_edit context.can_view = can_view or request.session.get("public_link") context.xform = xform context.content_user = xform.user context.base_url = "https://%s" % request.get_host() context.source = MetaData.source(xform) context.form_license = MetaData.form_license(xform).data_value context.data_license = MetaData.data_license(xform).data_value context.supporting_docs = MetaData.supporting_docs(xform) context.media_upload = MetaData.media_upload(xform) context.mapbox_layer = MetaData.mapbox_layer_upload(xform) if is_owner: context.sms_support_form = ActivateSMSSupportFom( initial={"enable_sms_support": xform.allows_sms, "sms_id_string": xform.sms_id_string} ) if not xform.allows_sms: context.sms_compatible = check_form_sms_compatibility(None, json_survey=json.loads(xform.json)) else: url_root = request.build_absolute_uri("/")[:-1] context.sms_providers_doc = providers_doc(url_root=url_root, username=username, id_string=id_string) context.url_root = url_root context.form_license_form = FormLicenseForm(initial={"value": context.form_license}) context.data_license_form = DataLicenseForm(initial={"value": context.data_license}) context.doc_form = SupportDocForm() context.source_form = SourceForm() context.media_form = MediaForm() context.mapbox_layer_form = MapboxLayerForm() users_with_perms = [] for perm in get_users_with_perms(xform, attach_perms=True).items(): has_perm = [] if "change_xform" in perm[1]: has_perm.append(_(u"Can Edit")) if "view_xform" in perm[1]: has_perm.append(_(u"Can View")) users_with_perms.append((perm[0], u" | ".join(has_perm))) context.users_with_perms = users_with_perms context.permission_form = PermissionForm(username) if xform.allows_sms: context.sms_support_doc = get_autodoc_for(xform) return render_to_response("show.html", context_instance=context)
def test_private_set_link_to_share_toggle_off(self): response = self.client.post(self.perm_url, {'for_user': '******', 'perm_type': 'link'}) self.assertEqual(MetaData.public_link(self.xform), True) response = self.anon.get(self.show_url) self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], '%s%s' % (self.base_url, self.show_normal_url)) response = self.client.post(self.perm_url, {'for_user': '******', 'perm_type': 'link'}) self.assertEqual(MetaData.public_link(self.xform), False) response = self.anon.get(self.show_url) # follow redirect response = self.anon.get(response['Location']) self.assertEqual(response.status_code, 302) self.assertNotEqual(response['Location'], '%s%s' % (self.base_url, self.show_normal_url))
def test_metadata_file_hash(self): self._publish_transportation_form() src = os.path.join(self.this_directory, "fixtures", "transportation", "screenshot.png") uf = UploadedFile(file=open(src), content_type='image/png') count = MetaData.objects.count() MetaData.media_upload(self.xform, uf) # assert successful insert of new metadata record self.assertEqual(MetaData.objects.count(), count + 1) md = MetaData.objects.get(xform=self.xform, data_value='screenshot.png') # assert checksum string has been generated, hash length > 1 self.assertTrue(len(md.hash) > 16) md.data_file.storage.delete(md.data_file.name) md = MetaData.objects.get(xform=self.xform, data_value='screenshot.png') self.assertEqual(len(md.hash), 0)
def set_perm(request, username, id_string): xform = get_object_or_404(XForm, user__username=username, id_string=id_string) try: perm_type = request.POST['perm_type'] for_user = request.POST['for_user'] except KeyError: return HttpResponseBadRequest() if perm_type in ['edit', 'view', 'remove']: user = User.objects.get(username=for_user) if perm_type == 'edit': assign('change_xform', user, xform) elif perm_type == 'view': assign('view_xform', user, xform) elif perm_type == 'remove': remove_perm('change_xform', user, xform) remove_perm('view_xform', user, xform) elif perm_type == 'link': if for_user == 'all': MetaData.public_link(xform, True) elif for_user == 'none': MetaData.public_link(xform, False) elif for_user == 'toggle': current = MetaData.public_link(xform) MetaData.public_link(xform, not current) return HttpResponseRedirect(reverse(show, kwargs={ 'username': username, 'id_string': id_string }))
def set_perm(request, username, id_string): xform = get_object_or_404(XForm, user__username=username, id_string=id_string) try: perm_type = request.POST["perm_type"] for_user = request.POST["for_user"] except KeyError: return HttpResponseBadRequest() if perm_type in ["edit", "view", "remove"]: user = User.objects.get(username=for_user) if perm_type == "edit": assign("change_xform", user, xform) elif perm_type == "view": assign("view_xform", user, xform) elif perm_type == "remove": remove_perm("change_xform", user, xform) remove_perm("view_xform", user, xform) elif perm_type == "link": if for_user == "all": MetaData.public_link(xform, True) elif for_user == "none": MetaData.public_link(xform, False) elif for_user == "toggle": current = MetaData.public_link(xform) MetaData.public_link(xform, not current) return HttpResponseRedirect(reverse(show, kwargs={"username": username, "id_string": id_string}))
def test_public_with_link_to_share(self): response = self.client.post(self.perm_url, {'for_user': '******', 'perm_type': 'link'}) self.assertEqual(response.status_code, 302) self.assertEqual(MetaData.public_link(self.xform), True) response = self.anon.get(self.show_url) self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], '%s%s' % (self.base_url, self.show_normal_url))
def test_public_with_link_to_share_toggle_on(self): response = self.client.post(self.perm_url, {'for_user': '******', 'perm_type': 'link'}) self.assertEqual(response.status_code, 302) self.assertEqual(MetaData.public_link(self.xform), True) response = self.anon.get(self.show_url) self.assertEqual(response.status_code, 302) response = self.anon.get(self.url) self.assertEqual(response.status_code, 302)
def test_only_access_shared_link_form(self): response = self.client.post(self.perm_url, {"for_user": "******", "perm_type": "link"}) self.assertEqual(MetaData.public_link(self.xform), True) # publish a second form to make sure the user cant access other forms self._publish_xls_file(os.path.join(self.this_directory, "fixtures", "csv_export", "tutorial.xls")) xform_2 = XForm.objects.order_by("pk").reverse()[0] url_2 = reverse(show, kwargs={"username": self.user.username, "id_string": xform_2.id_string}) response = self.anon.get(url_2) self.assertEqual(response.status_code, 302) self.assertEqual(response["Location"], "%s/" % self.base_url)
def test_public_with_link_to_share_toggle_on(self): response = self.client.post(self.perm_url, {'for_user': '******', 'perm_type': 'link'}) self.assertEqual(response.status_code, 302) self.assertEqual(MetaData.public_link(self.xform), True) response = self.anon.get(self.show_url) self.assertEqual(response.status_code, 302) response = self.anon.get(self.url) status_code = 200 if self._running_touchforms() else 302 self.assertEqual(response.status_code, status_code)
def map_view(request, username, id_string, template='map.html'): owner = get_object_or_404(User, username=username) xform = get_object_or_404(XForm, id_string=id_string, user=owner) if not has_permission(xform, owner, request): return HttpResponseForbidden(_(u'Not shared.')) context = RequestContext(request) context.content_user = owner context.xform = xform context.profile, created = UserProfile.objects.get_or_create(user=owner) points = ParsedInstance.objects.values('lat', 'lng', 'instance').filter( instance__user=owner, instance__xform__id_string=id_string, lat__isnull=False, lng__isnull=False) center = { 'lat': round_down_geopoint(average([p['lat'] for p in points])), 'lng': round_down_geopoint(average([p['lng'] for p in points])), } def round_down_point(p): return { 'lat': round_down_geopoint(p['lat']), 'lng': round_down_geopoint(p['lng']), 'instance': p['instance'] } context.center = json.dumps(center) context.form_view = True context.jsonform_url = reverse(download_jsonform, kwargs={"username": username, "id_string": id_string}) context.enketo_edit_url = reverse('edit_data', kwargs={"username": username, "id_string": id_string, "data_id": 0}) context.enketo_add_url = reverse('enter_data', kwargs={"username": username, "id_string": id_string}) context.enketo_add_with_url = reverse('add_submission_with', kwargs={"username": username, "id_string": id_string}) context.mongo_api_url = reverse('mongo_view_api', kwargs={"username": username, "id_string": id_string}) context.delete_data_url = reverse('delete_data', kwargs={"username": username, "id_string": id_string}) context.mapbox_layer = MetaData.mapbox_layer_upload(xform) audit = { "xform": xform.id_string } audit_log(Actions.FORM_MAP_VIEWED, request.user, owner, _("Requested map on '%(id_string)s'.") % {'id_string': xform.id_string}, audit, request) return render_to_response(template, context_instance=context)
def test_public_with_link_to_share(self): response = self.client.post(self.perm_url, { 'for_user': '******', 'perm_type': 'link' }) self.assertEqual(response.status_code, 302) self.assertEqual(MetaData.public_link(self.xform), True) response = self.anon.get(self.show_url) self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], '%s%s' % (self.base_url, self.show_normal_url))
def auto_add_crowd_form_to_registered_user(sender, **kwargs): new_user = kwargs.get("user") if ( hasattr(settings, "AUTO_ADD_CROWDFORM") and settings.AUTO_ADD_CROWDFORM and hasattr(settings, "DEFAULT_CROWDFORM") ): try: default_crowdform = settings.DEFAULT_CROWDFORM if ( isinstance(default_crowdform, dict) and "xform_username" in default_crowdform and "xform_id_string" in default_crowdform ): xform = XForm.objects.get( id_string=default_crowdform["xform_id_string"], user__username=default_crowdform["xform_username"] ) MetaData.crowdform_users(xform, new_user.username) except XForm.DoesNotExist: pass
def test_public_with_link_to_share_toggle_on(self): response = self.client.post(self.perm_url, {'for_user': '******', 'perm_type': 'link'}) self.assertEqual(response.status_code, 302) self.assertEqual(MetaData.public_link(self.xform), True) response = self.anon.get(self.show_url) self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], '%s%s' % (self.base_url, self.show_normal_url)) response = self.anon.get(self.show_normal_url) self.assertEqual(response.status_code, 200) self.assertContains(response, '/forms/%s' % self.xform.uuid)
def save(self, profile_callback=None): new_user = RegistrationProfile.objects.create_inactive_user( username=self.cleaned_data['username'], password=self.cleaned_data['password1'], email=self.cleaned_data['email']) UserProfileFormRegister.save(self, new_user) if hasattr(settings, 'AUTO_ADD_CROWDFORM') and \ settings.AUTO_ADD_CROWDFORM and \ hasattr(settings, 'DEFAULT_CROWDFORM'): try: default_crowdform = settings.DEFAULT_CROWDFORM if isinstance(default_crowdform, dict) and\ default_crowdform.has_key('xform_username') and\ default_crowdform.has_key('xform_id_string'): xform = XForm.objects.get( id_string=default_crowdform['xform_id_string'], user__username=default_crowdform['xform_username']) MetaData.crowdform_users(xform, new_user.username) except XForm.DoesNotExist: pass return new_user
def test_private_set_link_to_share_toggle_off(self): response = self.client.post(self.perm_url, { 'for_user': '******', 'perm_type': 'link' }) self.assertEqual(MetaData.public_link(self.xform), True) response = self.anon.get(self.show_url) self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], '%s%s' % (self.base_url, self.show_normal_url)) response = self.client.post(self.perm_url, { 'for_user': '******', 'perm_type': 'link' }) self.assertEqual(MetaData.public_link(self.xform), False) response = self.anon.get(self.show_url) # follow redirect response = self.anon.get(response['Location']) self.assertEqual(response.status_code, 302) self.assertNotEqual(response['Location'], '%s%s' % (self.base_url, self.show_normal_url))
def test_crowdform_for_new_user(self): # initial meta = MetaData.crowdform_users(self.xform) self.assertEqual(len(meta), 0) #save settings to be restored later old_auto_add_cf = settings.AUTO_ADD_CROWDFORM old_default_cf = settings.DEFAULT_CROWDFORM # enable auto add crowdform settings.AUTO_ADD_CROWDFORM = True settings.DEFAULT_CROWDFORM = { 'xform_username': self.user.username, 'xform_id_string': self.xform.id_string } # register new user post_data = { 'username': self.alice, 'email': '*****@*****.**', 'password1': 'bobbob', 'password2': 'bobbob', 'name': 'Alice', 'city': 'Ecila', 'country': 'US', 'organization': 'Alic Inc.', 'home_page': 'alice.com', 'twitter': 'alicerama' } url = '/accounts/register/' self.response = self.client.post(url, post_data) # check to ensure that crowd form was added meta = MetaData.crowdform_users(self.xform) self.assertEqual(len(meta), 1) self.assertEqual(meta[0].data_value, self.alice) # restore old settings settings.AUTO_ADD_CROWDFORM = old_auto_add_cf settings.DEFAULT_CROWDFORM = old_default_cf
def xformsManifest(request, username, id_string): xform = get_object_or_404(XForm, id_string=id_string, user__username=username) response = render_to_response("xformsManifest.xml", { #'urls': urls, 'host': request.build_absolute_uri()\ .replace(request.get_full_path(), ''), 'media_files': MetaData.media_upload(xform) }, mimetype="text/xml; charset=utf-8") response['X-OpenRosa-Version'] = '1.0' tz = pytz.timezone(settings.TIME_ZONE) dt = datetime.now(tz).strftime('%a, %d %b %Y %H:%M:%S %Z') response['Date'] = dt return response
def test_crowdform_for_new_user(self): # initial meta = MetaData.crowdform_users(self.xform) self.assertEqual(len(meta), 0) #save settings to be restored later old_auto_add_cf = settings.AUTO_ADD_CROWDFORM old_default_cf = settings.DEFAULT_CROWDFORM # enable auto add crowdform settings.AUTO_ADD_CROWDFORM = True settings.DEFAULT_CROWDFORM = { 'xform_username': self.user.username, 'xform_id_string': self.xform.id_string} # register new user post_data = { 'username': self.alice, 'email': '*****@*****.**', 'password1': 'bobbob', 'password2': 'bobbob', 'name': 'Alice', 'city': 'Ecila', 'country': 'US', 'organization': 'Alic Inc.', 'home_page': 'alice.com', 'twitter': 'alicerama' } url = '/accounts/register/' self.response = self.client.post(url, post_data) # check to ensure that crowd form was added meta = MetaData.crowdform_users(self.xform) self.assertEqual(len(meta), 1) self.assertEqual(meta[0].data_value, self.alice) # restore old settings settings.AUTO_ADD_CROWDFORM = old_auto_add_cf settings.DEFAULT_CROWDFORM = old_default_cf
def __init__(self, *args, **kwargs): super(Show, self).__init__(*args, **kwargs) if not self.metaData: meta = MetaData() self.metaData = meta try: if not self.genres: for artist in Artist.objects.filter(show__id=self.id): for genre in artist.genres.all(): self.genres.add(genre) self.save() except ValueError: print("Show not initialized")
def show(request, username=None, id_string=None, uuid=None): if uuid: xform = get_object_or_404(XForm, uuid=uuid) request.session['public_link'] = MetaData.public_link(xform) return HttpResponseRedirect(reverse(show, kwargs={ 'username': xform.user.username, 'id_string': xform.id_string })) xform, is_owner, can_edit, can_view = get_xform_and_perms( username, id_string, request) # no access if not (xform.shared or can_view or request.session.get('public_link')): return HttpResponseRedirect(reverse(home)) context = RequestContext(request) context.cloned = len( XForm.objects.filter(user__username=request.user.username, id_string=id_string + XForm.CLONED_SUFFIX) ) > 0 context.public_link = MetaData.public_link(xform) context.is_owner = is_owner context.can_edit = can_edit context.can_view = can_view or request.session.get('public_link') context.xform = xform context.content_user = xform.user context.base_url = "https://%s" % request.get_host() context.source = MetaData.source(xform) context.form_license = MetaData.form_license(xform).data_value context.data_license = MetaData.data_license(xform).data_value context.supporting_docs = MetaData.supporting_docs(xform) context.media_upload = MetaData.media_upload(xform) context.mapbox_layer = MetaData.mapbox_layer_upload(xform) if is_owner: context.form_license_form = FormLicenseForm( initial={'value': context.form_license}) context.data_license_form = DataLicenseForm( initial={'value': context.data_license}) context.doc_form = SupportDocForm() context.source_form = SourceForm() context.media_form = MediaForm() context.mapbox_layer_form = MapboxLayerForm() context.users_with_perms = get_users_with_perms( xform, attach_perms=True ).items() context.permission_form = PermissionForm(username) user_list = [u.username for u in User.objects.exclude(username=username)] context.user_json_list = simplejson.dumps(user_list) return render_to_response("show.html", context_instance=context)
def test_metadata_file_hash(self): self._publish_transportation_form() src = os.path.join(self.this_directory, "fixtures", "transportation","screenshot.png") uf = UploadedFile(file=open(src), content_type='image/png') count = MetaData.objects.count() rs = MetaData.media_upload(self.xform, uf) # assert successful insert of new metadata record self.assertEqual(MetaData.objects.count(), count + 1) md = MetaData.objects.get(xform=self.xform, data_value='screenshot.png') # assert checksum string has been generated, hash length > 1 self.assertTrue(len(md.hash) > 16) md.data_file.storage.delete(md.data_file.name) md = MetaData.objects.get(xform=self.xform, data_value='screenshot.png') self.assertEqual(len(md.hash), 0)
def test_public_with_link_to_share_toggle_on(self): response = self.client.post(self.perm_url, { 'for_user': '******', 'perm_type': 'link' }) self.assertEqual(response.status_code, 302) self.assertEqual(MetaData.public_link(self.xform), True) response = self.anon.get(self.show_url) self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], '%s%s' % (self.base_url, self.show_normal_url)) response = self.anon.get(self.show_normal_url) self.assertEqual(response.status_code, 200) self.assertContains(response, '/forms/%s' % self.xform.uuid)
def map_view(request, username, id_string, template='map.html'): owner = get_object_or_404(User, username=username) xform = get_object_or_404(XForm, id_string=id_string, user=owner) if not has_permission(xform, owner, request): return HttpResponseForbidden(_(u'Not shared.')) context = RequestContext(request) context.content_user = owner context.xform = xform context.profile, created = UserProfile.objects.get_or_create(user=owner) context.form_view = True context.jsonform_url = reverse(download_jsonform, kwargs={ "username": username, "id_string": id_string }) context.enketo_edit_url = reverse('edit_data', kwargs={ "username": username, "id_string": id_string, "data_id": 0 }) context.enketo_add_url = reverse('enter_data', kwargs={ "username": username, "id_string": id_string }) context.enketo_add_with_url = reverse('add_submission_with', kwargs={ "username": username, "id_string": id_string }) context.mongo_api_url = reverse('mongo_view_api', kwargs={ "username": username, "id_string": id_string }) context.delete_data_url = reverse('delete_data', kwargs={ "username": username, "id_string": id_string }) context.mapbox_layer = MetaData.mapbox_layer_upload(xform) audit = {"xform": xform.id_string} audit_log( Actions.FORM_MAP_VIEWED, request.user, owner, _("Requested map on '%(id_string)s'.") % {'id_string': xform.id_string}, audit, request) return render_to_response(template, context_instance=context)
def formList(request, username): """ This is where ODK Collect gets its download list. """ if username.lower() == 'crowdforms': xforms = XForm.objects.filter(is_crowd_form=True)\ .exclude(user__username=username) else: formlist_user = get_object_or_404(User, username=username) profile, created = \ UserProfile.objects.get_or_create(user=formlist_user) if profile.require_auth: response = helper_auth_helper(request) if response: return response # unauthorized if user in auth request does not match user in path # unauthorized if user not active if formlist_user.username != request.user.username or\ not request.user.is_active: return HttpResponseNotAuthorized() xforms = \ XForm.objects.filter(downloadable=True, user__username=username) # retrieve crowd_forms for this user crowdforms = XForm.objects.filter( metadata__data_type=MetaData.CROWDFORM_USERS, metadata__data_value=username ) xforms = chain(xforms, crowdforms) urls = [{ 'url': request.build_absolute_uri(xform.url()), 'text': xform.title if not xform.is_crowd_form else 'Crowd/%s' % xform.title, 'media': { 'm': MetaData.media_upload(xform), 'user': xform.user, 'id': xform.id_string } } for xform in xforms] return render_to_response("formList.xml", { 'urls': urls, 'host': 'http://%s' % request.get_host() }, mimetype="text/xml")
def show(request, username=None, id_string=None, uuid=None): if uuid: xform = get_object_or_404(XForm, uuid=uuid) request.session['public_link'] = MetaData.public_link(xform) return HttpResponseRedirect(reverse(show, kwargs={ 'username': xform.user.username, 'id_string': xform.id_string })) xform, is_owner, can_edit, can_view = get_xform_and_perms(username,\ id_string, request) # no access if not (xform.shared or can_view or request.session.get('public_link')): return HttpResponseRedirect(reverse(home)) context = RequestContext(request) context.cloned = len( XForm.objects.filter(user__username=request.user.username, id_string=id_string + XForm.CLONED_SUFFIX) ) > 0 context.public_link = MetaData.public_link(xform) context.is_owner = is_owner context.can_edit = can_edit context.can_view = can_view or request.session.get('public_link') context.xform = xform context.content_user = xform.user context.base_url = "https://%s" % request.get_host() context.source = MetaData.source(xform) context.form_license = MetaData.form_license(xform).data_value context.data_license = MetaData.data_license(xform).data_value context.supporting_docs = MetaData.supporting_docs(xform) context.media_upload = MetaData.media_upload(xform) context.mapbox_layer = MetaData.mapbox_layer_upload(xform) if is_owner: context.form_license_form = FormLicenseForm( initial={'value': context.form_license}) context.data_license_form = DataLicenseForm( initial={'value': context.data_license}) context.doc_form = SupportDocForm() context.source_form = SourceForm() context.media_form = MediaForm() context.mapbox_layer_form = MapboxLayerForm() context.users_with_perms = get_users_with_perms(xform, attach_perms=True).items() context.permission_form = PermissionForm(username) return render_to_response("show.html", context_instance=context)
def test_public_with_link_to_share_toggle_on(self): #sharing behavior as of 09/13/2012: #it requires both data_share and form_share both turned on #in order to grant anon access to form uploading #TODO: findout 'for_user': '******' and what it means response = self.client.post(self.perm_url, {'for_user': '******', 'perm_type': 'link'}) self.assertEqual(response.status_code, 302) self.assertEqual(MetaData.public_link(self.xform), True) #toggle shared on self.xform.shared = True self.xform.shared_data = True self.xform.save() response = self.anon.get(self.show_url) self.assertEqual(response.status_code, 302) response = self.anon.get(self.url) status_code = 302 if self._running_enketo() else 403 self.assertEqual(response.status_code, status_code)
def test_only_access_shared_link_form(self): response = self.client.post(self.perm_url, { 'for_user': '******', 'perm_type': 'link' }) self.assertEqual(MetaData.public_link(self.xform), True) # publish a second form to make sure the user cant access other forms self._publish_xls_file( os.path.join(self.this_directory, "fixtures", "csv_export", "tutorial.xls")) xform_2 = XForm.objects.order_by('pk').reverse()[0] url_2 = reverse(show, kwargs={ 'username': self.user.username, 'id_string': xform_2.id_string }) response = self.anon.get(url_2) self.assertEqual(response.status_code, 302) self.assertEqual(response["Location"], "%s/" % self.base_url)
def test_public_with_link_to_share_toggle_on(self): #sharing behavior as of 09/13/2012: #it requires both data_share and form_share both turned on #in order to grant anon access to form uploading #TODO: findout 'for_user': '******' and what it means response = self.client.post(self.perm_url, { 'for_user': '******', 'perm_type': 'link' }) self.assertEqual(response.status_code, 302) self.assertEqual(MetaData.public_link(self.xform), True) #toggle shared on self.xform.shared = True self.xform.shared_data = True self.xform.save() response = self.anon.get(self.show_url) self.assertEqual(response.status_code, 302) response = self.anon.get(self.url) status_code = 302 if self._running_enketo() else 403 self.assertEqual(response.status_code, status_code)
def xformsManifest(request, username, id_string): xform = get_object_or_404( XForm, id_string=id_string, user__username=username) formlist_user = xform.user profile, created = \ UserProfile.objects.get_or_create(user=formlist_user) if profile.require_auth: authenticator = HttpDigestAuthenticator() if not authenticator.authenticate(request): return authenticator.build_challenge_response() response = render_to_response("xformsManifest.xml", { #'urls': urls, 'host': request.build_absolute_uri().replace( request.get_full_path(), ''), 'media_files': MetaData.media_upload(xform) }, mimetype="text/xml; charset=utf-8") response['X-OpenRosa-Version'] = '1.0' tz = pytz.timezone(settings.TIME_ZONE) dt = datetime.now(tz).strftime('%a, %d %b %Y %H:%M:%S %Z') response['Date'] = dt return response
def map_view(request, username, id_string, template='map.html'): owner = get_object_or_404(User, username=username) xform = get_object_or_404(XForm, id_string=id_string, user=owner) if not has_permission(xform, owner, request): return HttpResponseForbidden(_(u'Not shared.')) context = RequestContext(request) context.content_user = owner context.xform = xform context.profile, created = UserProfile.objects.get_or_create(user=owner) context.form_view = True context.jsonform_url = reverse(download_jsonform, kwargs={"username": username, "id_string": id_string}) context.enketo_edit_url = reverse('edit_data', kwargs={"username": username, "id_string": id_string, "data_id": 0}) context.enketo_add_url = reverse('enter_data', kwargs={"username": username, "id_string": id_string}) context.enketo_add_with_url = reverse('add_submission_with', kwargs={"username": username, "id_string": id_string}) context.mongo_api_url = reverse('mongo_view_api', kwargs={"username": username, "id_string": id_string}) context.delete_data_url = reverse('delete_data', kwargs={"username": username, "id_string": id_string}) context.mapbox_layer = MetaData.mapbox_layer_upload(xform) audit = { "xform": xform.id_string } audit_log(Actions.FORM_MAP_VIEWED, request.user, owner, _("Requested map on '%(id_string)s'.") % {'id_string': xform.id_string}, audit, request) return render_to_response(template, context_instance=context)
def formList(request, username): render_formlist = False formlist_user = get_object_or_404(User, username=username) profile, created = UserProfile.objects.get_or_create(user=formlist_user) if profile.require_auth: # source, http://djangosnippets.org/snippets/243/ if 'HTTP_AUTHORIZATION' in request.META: auth = request.META['HTTP_AUTHORIZATION'].split() # NOTE: We are only support BASIC authentication for now. if len(auth) == 2 and auth[0].lower() == "basic": uname, passwd = base64.b64decode(auth[1]).split(':') # ensure listing this user's forms if formlist_user.username == uname: user = authenticate(username=uname, password=passwd) if user is not None and user.is_active: render_formlist = True else: render_formlist = True if render_formlist: """This is where ODK Collect gets its download list.""" xforms = XForm.objects.filter(downloadable=True, user__username=username) urls = [{ 'url': request.build_absolute_uri(xform.url()), 'text': xform.title, 'media': { 'm': MetaData.media_upload(xform), 'user': xform.user, 'id': xform.id_string } } for xform in xforms] return render_to_response("formList.xml", { 'urls': urls, 'host': 'http://%s' % request.get_host() }, mimetype="text/xml") return HttpResponseNotAuthorized('Must be logged in')
def test_public_with_link_to_share_toggle_on(self): #sharing behavior as of 09/13/2012: #it requires both data_share and form_share both turned on #in order to grant anon access to form uploading #TODO: findout 'for_user': '******' and what it means response = self.client.post(self.perm_url, {'for_user': '******', 'perm_type': 'link'}) self.assertEqual(response.status_code, 302) self.assertEqual(MetaData.public_link(self.xform), True) #toggle shared on self.xform.shared = True self.xform.shared_data = True self.xform.save() response = self.anon.get(self.show_url) self.assertEqual(response.status_code, 302) if not self._running_enketo(): raise SkipTest with HTTMock(enketo_mock): factory = RequestFactory() request = factory.get('/') request.user = AnonymousUser() response = enter_data( request, self.user.username, self.xform.id_string) self.assertEqual(response.status_code, 302)
def show(request, username=None, id_string=None, uuid=None): if uuid: xform = get_object_or_404(XForm, uuid=uuid) request.session['public_link'] = MetaData.public_link(xform) return HttpResponseRedirect(reverse(show, kwargs={ 'username': xform.user.username, 'id_string': xform.id_string })) xform, is_owner, can_edit, can_view = get_xform_and_perms(username,\ id_string, request) # no access if not (xform.shared or can_view or request.session.get('public_link')): return HttpResponseRedirect(reverse(home)) context = RequestContext(request) context.public_link = MetaData.public_link(xform) context.is_owner = is_owner context.can_edit = can_edit context.can_view = can_view or request.session.get('public_link') context.xform = xform context.content_user = xform.user context.base_url = "https://%s" % request.get_host() context.source = MetaData.source(xform) context.form_license = MetaData.form_license(xform).data_value context.data_license = MetaData.data_license(xform).data_value context.supporting_docs = MetaData.supporting_docs(xform) if is_owner: context.form_license_form = FormLicenseForm( initial={'value': context.form_license}) context.data_license_form = DataLicenseForm( initial={'value': context.data_license}) context.doc_form = SupportDocForm() context.source_form = SourceForm() context.users_with_perms = get_users_with_perms(xform, attach_perms=True).items() context.permission_form = PermissionForm(username) return render_to_response("show.html", context_instance=context)
def test_upload_source_file_set_value_to_name(self): name = self._add_metadata('source') self.assertEqual(MetaData.source(self.xform).data_value, name)
def _add_crowdform(self): self._create_user_and_login(self.alice, self.alice) self.assertEqual(len(MetaData.crowdform_users(self.xform)), self.crowdform_count) self.response = self.client.get(self.edit_url, {'crowdform': 'add'}) self.crowdform_count += 1
def test_user_add_crowdform(self): self._add_crowdform() self.assertEqual(self.response.status_code, 302) meta = MetaData.crowdform_users(self.xform) self.assertEqual(len(meta), 1) self.assertEqual(meta[0].data_value, self.alice)
def test_user_delete_crowdform(self): self._add_crowdform() self.response = self.client.get(self.edit_url, {'crowdform': 'delete'}) meta = MetaData.crowdform_users(self.xform) self.assertEqual(len(meta), 0) self.assertEqual(self.response.status_code, 302)
def __init__(self, *args, **kwargs): super(YoutubeVideo, self).__init__(*args, **kwargs) if not self.metaData: meta = MetaData() self.metaData = meta
def __init__(self, *args, **kwargs): super(InfoPage, self).__init__(*args, **kwargs) if not self.metaData: meta = MetaData() self.metaData = meta
def edit(request, username, id_string): xform = XForm.objects.get(user__username=username, id_string=id_string) if username == request.user.username or\ request.user.has_perm('odk_logger.change_xform', xform): if request.POST.get('description'): xform.description = request.POST['description'] elif request.POST.get('title'): xform.title = request.POST['title'] elif request.POST.get('toggle_shared'): if request.POST['toggle_shared'] == 'data': xform.shared_data = not xform.shared_data elif request.POST['toggle_shared'] == 'form': xform.shared = not xform.shared elif request.POST['toggle_shared'] == 'active': xform.downloadable = not xform.downloadable elif request.POST.get('form-license'): MetaData.form_license(xform, request.POST['form-license']) elif request.POST.get('data-license'): MetaData.data_license(xform, request.POST['data-license']) elif request.POST.get('source') or request.FILES.get('source'): MetaData.source(xform, request.POST.get('source'), request.FILES.get('source')) elif request.FILES.get('media'): MetaData.media_upload(xform, request.FILES.get('media')) elif request.POST.get('map_name'): mapbox_layer = MapboxLayerForm(request.POST) if mapbox_layer.is_valid(): MetaData.mapbox_layer_upload(xform, mapbox_layer.cleaned_data) elif request.FILES: MetaData.supporting_docs(xform, request.FILES['doc']) xform.update() if request.is_ajax(): return HttpResponse('Updated succeeded.') else: return HttpResponseRedirect(reverse(show, kwargs={ 'username': username, 'id_string': id_string })) return HttpResponseForbidden('Update failed.')
def __init__(self, *args, **kwargs): super(Artist, self).__init__(*args, **kwargs) if not self.metaData: meta = MetaData() self.metaData = meta
def test_upload_source_file(self): name = self._add_metadata('source') self.assertNotEqual(MetaData.source(self.xform).data_file, None)
def test_user_data_license_edit_updates(self): desc = 'Snooky' response = self.client.post(self.edit_url, {'data-license': desc}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 200) self.assertEqual(MetaData.data_license(self.xform).data_value, desc)