def deprecate(request, iid): item = get_object_or_404(MDR._concept, pk=iid).item if not (item and user_can_edit(request.user, item)): if request.user.is_anonymous(): return redirect(reverse('friendly_login') + '?next=%s' % request.path) else: raise PermissionDenied qs=item.__class__.objects.filter().editable(request.user) if request.method == 'POST': # If the form has been submitted... form = MDRForms.DeprecateForm(request.POST, user=request.user, item=item, qs=qs) # A form bound to the POST data if form.is_valid(): # Check use the itemset as there are permissions issues and we want to remove some: # Everything that was superseded, but isn't in the returned set # Everything that was in the returned set, but isn't already superseded # Everything left over can stay the same, as its already superseded # or wasn't superseded and is staying that way. with transaction.atomic(), reversion.revisions.create_revision(): reversion.revisions.set_user(request.user) for i in item.supersedes.all(): if i not in form.cleaned_data['olderItems'] and user_can_edit(request.user, i): item.supersedes.remove(i) for i in form.cleaned_data['olderItems']: if user_can_edit(request.user, i): # Would check item.supersedes but its a set item.supersedes.add(i) return HttpResponseRedirect(url_slugify_concept(item)) else: form = MDRForms.DeprecateForm(user=request.user, item=item, qs=qs) return render(request, "aristotle_mdr/actions/deprecateItems.html", {"item": item, "form": form})
def deprecate(request, iid): item = get_object_or_404(MDR._concept, pk=iid).item if not (item and user_can_edit(request.user, item)): if request.user.is_anonymous(): return redirect(reverse("friendly_login") + "?next=%s" % request.path) else: raise PermissionDenied qs = item.__class__.objects.filter().editable(request.user) if request.method == "POST": # If the form has been submitted... form = MDRForms.DeprecateForm( request.POST, user=request.user, item=item, qs=qs ) # A form bound to the POST data if form.is_valid(): # Check use the itemset as there are permissions issues and we want to remove some: # Everything that was superseded, but isn't in the returned set # Everything that was in the returned set, but isn't already superseded # Everything left over can stay the same, as its already superseded # or wasn't superseded and is staying that way. with transaction.atomic(), reversion.revisions.create_revision(): reversion.revisions.set_user(request.user) for i in item.supersedes.all(): if i not in form.cleaned_data["olderItems"] and user_can_edit(request.user, i): item.supersedes.remove(i) for i in form.cleaned_data["olderItems"]: if user_can_edit(request.user, i): # Would check item.supersedes but its a set item.supersedes.add(i) return HttpResponseRedirect(url_slugify_concept(item)) else: form = MDRForms.DeprecateForm(user=request.user, item=item, qs=qs) return render(request, "aristotle_mdr/actions/deprecateItems.html", {"item": item, "form": form})
def has_perm(self, user_obj, perm, obj=None): if not user_obj.is_active: return False if user_obj.is_superuser: return True app_label, perm_name = perm.split('.', 1) extensions = getattr(settings, 'ARISTOTLE_SETTINGS', {}).get('CONTENT_EXTENSIONS', []) if app_label == "aristotle_mdr" and hasattr(perms, perm_name): return getattr(perms, perm_name)(user_obj, obj) if app_label in extensions + ["aristotle_mdr"]: # This is required so that a user can correctly delete the 'concept' parent class in the admin site. if perm_name == "delete_concept_from_admin": return obj is None or perms.user_can_edit(user_obj, obj) # This is a rough catch all, and is designed to indicate a user could # delete an item type, but not a specific item. elif (perm_name.startswith('delete_') or perm_name.startswith('create_') or perm_name.startswith('add_')): if obj is None: return perms.user_is_editor(user_obj) else: return perms.user_can_edit(user_obj, obj) return super(AristotleBackend, self).has_perm(user_obj, perm, obj)
def test_canEditProfile(self): u1 = get_user_model().objects.create_user('*****@*****.**','user1') u2 = get_user_model().objects.create_user('*****@*****.**','user2') self.assertFalse(perms.user_can_edit(u1,u2)) self.assertFalse(perms.user_can_edit(u2,u1)) self.assertTrue(perms.user_can_edit(u1,u1)) self.assertTrue(perms.user_can_edit(u2,u2))
def has_perm(self, user_obj, perm, obj=None): if not user_obj.is_active: return False if user_obj.is_superuser: return True app_label,perm_name = perm.split('.',1) extensions = getattr(settings, 'ARISTOTLE_SETTINGS', {}).get('CONTENT_EXTENSIONS',[]) if app_label in extensions + ["aristotle_mdr"]: # This is required so that a user can correctly delete the 'concept' parent class in the admin site. if perm_name == "delete_concept_from_admin": return obj is None or perms.user_can_edit(user_obj,obj) # This is a rough catch all, and is designed to indicate a user could # delete an item type, but not a specific item. elif perm_name.startswith('delete_') \ or perm_name.startswith('create_') \ or perm_name.startswith('add_') : if obj is None: return perms.user_is_editor(user_obj) else: return perms.user_can_edit(user_obj,obj) if perm.startswith("aristotle_mdr.delete_"): if obj is None and perm is not "aristotle_mdr.delete_concept_from_admin": # This is a rough catch all, and will fail for extension items. return perms.user_is_editor(user_obj) if perm == "aristotle_mdr.delete_concept_from_admin": return obj is None or perms.user_can_edit(user_obj,obj) return super(AristotleBackend, self).has_perm(user_obj, perm, obj)
def test_canEditProfile(self): u1 = User.objects.create_user('user1','','user1') u2 = User.objects.create_user('user2','','user2') self.assertFalse(perms.user_can_edit(u1,u2)) self.assertFalse(perms.user_can_edit(u2,u1)) self.assertTrue(perms.user_can_edit(u1,u1)) self.assertTrue(perms.user_can_edit(u2,u2))
def test_canEditProfile(self): u1 = User.objects.create_user('user1', '', 'user1') u2 = User.objects.create_user('user2', '', 'user2') self.assertFalse(perms.user_can_edit(u1, u2)) self.assertFalse(perms.user_can_edit(u2, u1)) self.assertTrue(perms.user_can_edit(u1, u1)) self.assertTrue(perms.user_can_edit(u2, u2))
def test_managersCanEditWorkgroups(self): wg = models.Workgroup.objects.create( name="Test WG 1", stewardship_organisation=self.steward_org_1) user1 = get_user_model().objects.create_user('*****@*****.**', 'manager') user2 = get_user_model().objects.create_user('*****@*****.**', 'viewer') wg.giveRoleToUser('manager', user1) wg.giveRoleToUser('viewer', user2) wg.save() wg = models.Workgroup.objects.get(pk=wg.id) self.assertTrue(perms.user_in_workgroup(user1, wg)) self.assertTrue(perms.user_in_workgroup(user2, wg)) self.assertTrue(perms.user_can_view(user2, wg)) self.assertTrue(perms.user_can_view(user1, wg)) self.assertTrue(perms.user_can_edit(user1, wg)) self.assertFalse(perms.user_can_edit(user2, wg)) wg.removeUser(user1) wg.removeUser(user2) # Caching issue, refresh from DB with correct permissions user1 = get_user_model().objects.get(pk=user1.pk) user2 = get_user_model().objects.get(pk=user2.pk) self.assertFalse(perms.user_can_edit(user1, wg)) self.assertFalse(perms.user_can_edit(user2, wg))
def save(self, *args, **kwargs): instance = super(AdminConceptForm, self).save(*args, **kwargs) for i in instance.supersedes.all(): if user_can_edit(self.request.user, i) and i not in self.cleaned_data['deprecated']: instance.supersedes.remove(i) for i in self.cleaned_data['deprecated']: if user_can_edit(self.request.user, i): # Would check item.supersedes but its a set instance.supersedes.add(i) return instance
def save(self, *args, **kwargs): instance = super().save(*args, **kwargs) for i in instance.supersedes.all(): if user_can_edit(self.request.user, i) and i not in self.cleaned_data['deprecated']: instance.supersedes.remove(i) for i in self.cleaned_data['deprecated']: if user_can_edit(self.request.user, i): # Would check item.supersedes but its a set kwargs = {} if django_version > (1, 9): kwargs = {'bulk': False} instance.supersedes.add(i, **kwargs) return instance
def clean_newerItem(self): item = self.cleaned_data['newerItem'] if self.item.id == item.id: raise forms.ValidationError("An item may not supersede itself") if not user_can_edit(self.user,item): raise forms.ValidationError("You cannot supersede with an item that you do not have permission to edit") return item
def editClusterInclusion(request, dss_id, cluster_id): dss = get_object_or_404(models.DataSetSpecification, id=dss_id) cluster = get_object_or_404(models.DataSetSpecification, id=cluster_id) if not (user_can_edit(request.user, dss) and user_can_view(request.user, cluster)): raise PermissionDenied inclusion = get_object_or_404(models.DSSClusterInclusion, child=cluster, dss=dss) if request.method == 'POST': form = forms.EditClusterInclusionForm( request.POST, instance=inclusion) # , user=request.user) if form.is_valid(): with reversion.revisions.create_revision(): form.save() dss.save() reversion.set_comment('Edited cluster inclusion') return HttpResponseRedirect( reverse("aristotle_mdr:item", args=[dss.id])) else: form = forms.EditClusterInclusionForm( instance=inclusion) # , user=request.user) return render(request, "aristotle_dse/actions/edit_inclusion.html", { "item": inclusion, "form": form, })
def clone_item(request, iid, *args, **kwargs): item_to_clone = get_object_or_404(MDR._concept, pk=iid).item if not user_can_edit(request.user, item_to_clone): if request.user.is_anonymous(): return redirect( reverse('friendly_login') + '?next=%s' % request.path) else: raise PermissionDenied base_form = MDRForms.wizards.subclassed_modelform(item_to_clone.__class__) if request.method == 'POST': # If the form has been submitted... form = base_form(request.POST, user=request.user) if form.is_valid(): with transaction.atomic(), reversion.revisions.create_revision(): new_clone = form.save() reversion.revisions.set_user(request.user) reversion.revisions.set_comment( "Cloned from %s (id: %s)" % (item_to_clone.name, str(item_to_clone.pk))) return HttpResponseRedirect(url_slugify_concept(new_clone)) else: form = base_form(initial=concept_to_clone_dict(item_to_clone), user=request.user) return render(request, "aristotle_mdr/create/clone_item.html", { "item": item_to_clone, "form": form })
def addClustersToDSS(request, dss_id): dss = get_object_or_404(aristotle_dse.models.DataSetSpecification, id=dss_id) if not user_can_edit(request.user, dss): raise PermissionDenied qs = aristotle_dse.models.DataSetSpecification.objects.filter().visible(request.user) if request.method == 'POST': form = forms.AddClustersToDSSForm(request.POST, user=request.user, qs=qs, dss=dss) if form.is_valid(): cardinality = form.cleaned_data['cardinality'] maxOccurs = form.cleaned_data['maximum_occurances'] for child_dss in form.cleaned_data['clusters']: dss.addCluster( child=child_dss, maximum_occurances=maxOccurs, cardinality=cardinality ) return HttpResponseRedirect(reverse("aristotle_mdr:item", args=[dss.id])) else: form = forms.AddClustersToDSSForm(user=request.user, qs=qs, dss=dss) return render( request, "aristotle_dse/actions/addClustersToDSS.html", { "item": dss, "form": form, } )
def test_editor_change_item(self): self.login_editor() response = self.client.get(reverse("admin:%s_%s_change"%(self.itemType._meta.app_label,self.itemType._meta.model_name),args=[self.item1.pk])) self.assertResponseStatusCodeEqual(response,200) updated_item = dict((k,v) for (k,v) in model_to_dict(self.item1).items() if v is not None) updated_name = updated_item['name'] + " updated!" updated_item['name'] = updated_name updated_item.update({ 'statuses-TOTAL_FORMS': 0, 'statuses-INITIAL_FORMS': 0 # no statuses }) updated_item.update(self.form_defaults) self.assertTrue(self.wg1 in self.editor.profile.editable_workgroups.all()) self.assertEqual([self.wg1],list(response.context['adminform'].form.fields['workgroup'].queryset)) self.assertTrue(perms.user_can_edit(self.editor,self.item1)) self.assertTrue(self.item1.workgroup in self.editor.profile.editable_workgroups.all()) response = self.client.post( reverse("admin:%s_%s_change"%(self.itemType._meta.app_label,self.itemType._meta.model_name),args=[self.item1.id]), updated_item ) self.assertResponseStatusCodeEqual(response,302) self.item1 = self.itemType.objects.get(pk=self.item1.pk) self.assertEqual(self.item1.name,updated_name)
def addClustersToDSS(request, dss_id): dss = get_object_or_404(aristotle_dse.models.DataSetSpecification, id=dss_id) if not user_can_edit(request.user, dss): raise PermissionDenied qs = aristotle_dse.models.DataSetSpecification.objects.filter().visible( request.user) if request.method == 'POST': form = forms.AddClustersToDSSForm(request.POST, user=request.user, qs=qs, dss=dss) if form.is_valid(): cardinality = form.cleaned_data['cardinality'] maxOccurs = form.cleaned_data['maximum_occurances'] for child_dss in form.cleaned_data['clusters']: dss.addCluster(child=child_dss, maximum_occurances=maxOccurs, cardinality=cardinality) return HttpResponseRedirect( reverse("aristotle_mdr:item", args=[dss.id])) else: form = forms.AddClustersToDSSForm(user=request.user, qs=qs, dss=dss) return render(request, "aristotle_dse/actions/addClustersToDSS.html", { "item": dss, "form": form, })
def addClustersToDSS(request, dss_id): dss = get_object_or_404(models.DataSetSpecification, id=dss_id) if not user_can_edit(request.user, dss): raise PermissionDenied qs = models.DataSetSpecification.objects.filter().visible(request.user) if request.method == 'POST': form = forms.AddClustersToDSSForm(request.POST, user=request.user, qs=qs, dss=dss) if form.is_valid(): inclusion = form.cleaned_data['inclusion'] maxOccurs = form.cleaned_data['maximum_occurrences'] with reversion.revisions.create_revision(): for child_dss in form.cleaned_data['clusters']: dss.addCluster(child=child_dss, maximum_occurrences=maxOccurs, inclusion=inclusion) dss.save() reversion.set_comment('Added clusters') return HttpResponseRedirect( reverse("aristotle_mdr:item", args=[dss.id])) else: form = forms.AddClustersToDSSForm(user=request.user, qs=qs, dss=dss) return render(request, "aristotle_dse/actions/addClustersToDSS.html", { "item": dss, "form": form, })
def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) # Set objects context['object'] = self.issue context['comments'] = self.issue.comments.select_related( 'author__profile').all().order_by('created') # Set permissions can_edit_item = perms.user_can_edit(self.request.user, self.issue.item) own_issue = (self.request.user.id == self.issue.submitter.id) has_proposed_changes = (self.issue.proposal_field and self.issue.proposal_value) item_changed = self.issue.modified < self.issue.item.modified context.update({ 'can_open_close': (own_issue or can_edit_item), 'own_issue': own_issue, 'can_approve': can_edit_item, 'has_proposed_changes': has_proposed_changes, 'item_changed': item_changed, # Loaded by root component 'issue_data': { 'isopen': self.issue.isopen }, }) # Add diff table diff_table = '' if has_proposed_changes: diff_table = self.get_diff_table(self.issue.proposal_field, self.issue.proposal_value) context['diff_table'] = diff_table # Get data for modal context.update(self.get_modal_data(self.issue)) return context
def supersede(request, iid): item = get_object_or_404(MDR._concept, pk=iid).item if not (item and user_can_edit(request.user, item)): if request.user.is_anonymous(): return redirect( reverse('friendly_login') + '?next=%s' % request.path) else: raise PermissionDenied qs = item.__class__.objects.all() if request.method == 'POST': # If the form has been submitted... form = MDRForms.SupersedeForm(request.POST, user=request.user, item=item, qs=qs) # A form bound to the POST data if form.is_valid(): with transaction.atomic(), reversion.revisions.create_revision(): reversion.revisions.set_user(request.user) item.superseded_by = form.cleaned_data['newerItem'] item.save() return HttpResponseRedirect(url_slugify_concept(item)) else: form = MDRForms.SupersedeForm(item=item, user=request.user, qs=qs) return render(request, "aristotle_mdr/actions/supersedeItem.html", { "item": item, "form": form })
def test_propose_supersede(self): self.login_editor() self.assertTrue(perms.user_can_edit(self.editor, self.item1)) # Get formset postdata for single supersedes postdata = self.get_formset_postdata( [{ 'older_item': self.item2.id, 'registration_authority': self.ra.id, 'message': '', 'date_effective': '' }], prefix='superseded_items_relation_set') response = self.reverse_post( 'aristotle:proposed_supersede', postdata, reverse_args=[self.item1.id], ) self.assertRedirects(response, url_slugify_concept(self.item1)) self.assertEqual(self.item1.superseded_items_relation_set.count(), 1) ss = self.item1.superseded_items_relation_set.first() self.assertTrue(ss.proposed)
def edit_item(request,iid,*args,**kwargs): item = get_object_or_404(MDR._concept,pk=iid).item if not user_can_edit(request.user, item): if request.user.is_anonymous(): return redirect(reverse('django.contrib.auth.views.login')+'?next=%s' % request.path) else: raise PermissionDenied base_form = MDRForms.wizards.subclassed_edit_modelform(item.__class__) if request.method == 'POST': # If the form has been submitted... form = base_form(request.POST,instance=item,user=request.user) if form.is_valid(): with transaction.atomic(), reversion.create_revision(): change_comments = form.data.get('change_comments',None) item = form.save() reversion.set_user(request.user) if not change_comments: change_comments = construct_change_message(request,form,None) reversion.set_comment(change_comments) return HttpResponseRedirect(url_slugify_concept(item)) else: form = base_form(instance=item,user=request.user) return render(request,"aristotle_mdr/actions/advanced_editor.html", {"item":item, "form":form, } )
def editInclusionOrder(request, dss_id, inc_type): if inc_type not in ['cluster', 'data_element']: raise Http404 item = get_object_or_404(aristotle_dse.models.DataSetSpecification, pk=dss_id) if not user_can_edit(request.user, item): if request.user.is_anonymous(): return redirect(reverse('friendly_login') + '?next=%s' % request.path) else: raise PermissionDenied item_type, field_name = { 'cluster': (aristotle_dse.models.DSSClusterInclusion, 'child'), 'data_element': (aristotle_dse.models.DSSDEInclusion, 'data_element'), }.get(inc_type) num_values = item_type.objects.filter(dss=item.id).count() if num_values > 0: extra = 0 else: extra = 1 ValuesFormSet = modelformset_factory( item_type, formset=HiddenOrderModelFormSet, can_order=True, fields=('id',), extra=extra ) if request.method == 'POST': formset = ValuesFormSet(request.POST, request.FILES) if formset.is_valid(): with transaction.atomic(), reversion.create_revision(): item.save() # do this to ensure we are saving reversion records for the DSS, not just the values formset.save(commit=False) for form in formset.forms: if form['id'].value() not in [deleted_record['id'].value() for deleted_record in formset.deleted_forms]: inc = item_type.objects.get(pk=form['id'].value()) if inc.dss != item: raise PermissionDenied inc.order = form['ORDER'].value() # inc.maximum_occurances = form['maximum_occurances'].value() # value = form.save(commit=False) #Don't immediately save, we need to attach the value domain # value.dss = item inc.save() for obj in formset.deleted_objects: obj.delete() reversion.set_user(request.user) reversion.set_comment(construct_change_message(request, None, [formset, ])) return redirect(reverse("aristotle_mdr:item", args=[item.id])) else: formset = ValuesFormSet( queryset=item_type.objects.filter(dss=item.id), ) return render( request, "aristotle_dse/actions/edit_inclusion_order.html", {'item': item, 'formset': formset, 'include_type': inc_type, 'value_model': item_type, } )
def edit_item(request, iid, *args, **kwargs): item = get_object_or_404(MDR._concept, pk=iid).item if not user_can_edit(request.user, item): if request.user.is_anonymous(): return redirect(reverse('friendly_login') + '?next=%s' % request.path) else: raise PermissionDenied base_form = MDRForms.wizards.subclassed_edit_modelform(item.__class__) if request.method == 'POST': # If the form has been submitted... form = base_form(request.POST, instance=item, user=request.user) new_wg = request.POST.get('workgroup', None) workgroup_changed = not(str(item.workgroup.pk) == (new_wg)) if form.is_valid(): workgroup_changed = item.workgroup.pk != form.cleaned_data['workgroup'].pk with transaction.atomic(), reversion.revisions.create_revision(): change_comments = form.data.get('change_comments', None) item = form.save() reversion.revisions.set_user(request.user) if not change_comments: change_comments = construct_change_message(request, form, None) reversion.revisions.set_comment(change_comments) return HttpResponseRedirect(url_slugify_concept(item)) else: form = base_form(instance=item, user=request.user) return render(request, "aristotle_mdr/actions/advanced_editor.html", {"item": item, "form": form})
def editDataElementInclusion(request, dss_id, de_id): dss = get_object_or_404(aristotle_dse.models.DataSetSpecification, id=dss_id) de = get_object_or_404(aristotle.models.DataElement, id=de_id) if not (user_can_edit(request.user, dss) and user_can_view(request.user, de)): raise PermissionDenied inclusion = get_object_or_404(aristotle_dse.models.DSSDEInclusion, data_element=de, dss=dss) if request.method == 'POST': form = forms.EditDataElementInclusionForm( request.POST, instance=inclusion) # , user=request.user) if form.is_valid(): form.save() return HttpResponseRedirect( reverse("aristotle_mdr:item", args=[dss.id])) else: form = forms.EditDataElementInclusionForm( instance=inclusion) # , user=request.user) return render(request, "aristotle_dse/actions/edit_inclusion.html", { "item": inclusion, "form": form, })
def test_editor_deleting_allowed_item(self): self.login_editor() before_count = self.wg1.items.count() self.assertEqual(self.wg1.items.count(),1) response = self.client.get(reverse("admin:%s_%s_delete"%(self.itemType._meta.app_label,self.itemType._meta.model_name),args=[self.item1.pk])) self.assertResponseStatusCodeEqual(response,200) response = self.client.post( reverse("admin:%s_%s_delete"%(self.itemType._meta.app_label,self.itemType._meta.model_name),args=[self.item1.pk]), {'post':'yes'} ) self.assertRedirects(response,reverse("admin:%s_%s_changelist"%(self.itemType._meta.app_label,self.itemType._meta.model_name))) self.assertEqual(self.wg1.items.count(),before_count-1) self.assertFalse(self.itemType.objects.filter(pk=self.item1.pk).exists()) self.item1 = self.itemType.objects.create(name="OC1",workgroup=self.wg1, **self.create_defaults) self.assertEqual(self.wg1.items.count(),1) before_count = self.wg1.items.count() self.make_review_request(self.item1, self.registrar) old_count = self.item1.statuses.count() self.ra.register(self.item1,models.STATES.standard,self.registrar) self.assertTrue(self.item1.statuses.count() == old_count + 1) self.item1 = self.itemType.objects.get(pk=self.item1.pk) # Dang DB cache self.assertTrue(self.item1.is_registered) self.assertTrue(self.item1.is_locked()) self.assertFalse(perms.user_can_edit(self.editor,self.item1)) before_count = self.wg1.items.count() response = self.client.get( reverse( "admin:%s_%s_delete"%(self.itemType._meta.app_label,self.itemType._meta.model_name), args=[self.item1.pk] ), follow=True ) # In django 1.11, if you can't view an item you are redirected to the admin index page self.assertRedirects(response, reverse("admin:index")) self.assertContains(response, "Perhaps it was deleted?") self.assertTrue(self.itemType.objects.filter(pk=self.item1.pk).exists()) self.assertEqual(self.wg1.items.count(),before_count) response = self.client.post( reverse( "admin:%s_%s_delete"%(self.itemType._meta.app_label,self.itemType._meta.model_name), args=[self.item1.pk] ), {'post':'yes'}, follow=True ) # In django 1.11, if you can't view an item you are redirected to the admin index page self.assertRedirects(response, reverse("admin:index")) self.assertContains(response, "Perhaps it was deleted?") self.assertEqual(self.wg1.items.count(),before_count) self.assertTrue(self.itemType.objects.filter(pk=self.item1.pk).exists())
def removeDataElementFromDSS(request,de_id,dss_id): de = get_object_or_404(aristotle.models.DataElement,id=de_id) dss = get_object_or_404(aristotle_dse.models.DataSetSpecification,id=dss_id) if user_can_view(request.user,de) and user_can_edit(request.user,dss): dss.dataElements.filter(dataElement=de).delete() else: raise PermissionDenied return HttpResponseRedirect(reverse("aristotle_dse:%s"%dss.template_name(),args=[dss.id]))
def clean_olderItems(self): olderItems = self.cleaned_data['olderItems'] if self.item in olderItems: raise forms.ValidationError("An item may not supersede itself") for i in olderItems: if not user_can_edit(self.user,i): raise forms.ValidationError("You cannot supersede an item that you do not have permission to edit") return olderItems
def test_can_edit_cache(self): self.assertTrue(perms.user_can_edit(self.submitter, self.item)) self.item.definition = "edit name, then quickly check permission" self.item.save() self.assertTrue(perms.user_can_edit(self.submitter, self.item)) self.item.definition = "edit name, then wait 30 secs for 'recently edited to expire'" self.item.save() sleep(models.VERY_RECENTLY_SECONDS + 2) self.assertTrue(perms.user_can_edit(self.submitter, self.item)) # register then immediately check the permissions to make sure the cache is ignored # technically we haven't edited the item yet, although ``concept.recache_states`` will be called. reg, c = models.Status.objects.get_or_create( concept=self.item, registrationAuthority=self.ra, registrationDate=datetime.date(2009, 4, 28), state=models.STATES.standard) self.assertFalse(perms.user_can_edit(self.submitter, self.item))
def has_change_permission(self, request,obj=None): if obj is None: return True else: if perms.user_can_edit(request.user,obj): return True else: return super(ConceptAdmin, self).has_change_permission(request,obj=None)
def editInclusionDetails(request, dss_id, inc_type, cluster_id): dss = get_object_or_404(models.DataSetSpecification, id=dss_id) if inc_type not in ['cluster', 'data_element']: raise Http404 item = get_object_or_404(models.DataSetSpecification, pk=dss_id) if not user_can_edit(request.user, item): if request.user.is_anonymous: return redirect( reverse('friendly_login') + '?next=%s' % request.path) else: raise PermissionDenied item_type, field_name = { 'cluster': (models.DataSetSpecification, 'child'), 'data_element': (aristotle_models.DataElement, 'data_element'), }.get(inc_type) cluster = get_object_or_404(item_type, id=cluster_id) if not (user_can_edit(request.user, dss) and user_can_view(request.user, cluster_id)): raise PermissionDenied inclusion = get_object_or_404(models.DSSClusterInclusion, child=cluster, dss=dss) if request.method == 'POST': form = forms.EditClusterInclusionForm( request.POST, instance=inclusion) # , user=request.user) if form.is_valid(): with reversion.revisions.create_revision(): form.save() dss.save() reversion.set_comment('Edited inclusion details') return HttpResponseRedirect( reverse("aristotle_mdr:item", args=[dss.id])) else: form = forms.EditClusterInclusionForm( instance=inclusion) # , user=request.user) return render(request, "aristotle_dse/actions/edit_inclusion.html", { "item": inclusion, "form": form, "include_type": inc_type, })
def clean_newerItem(self): item = self.cleaned_data['newerItem'] if self.item.id == item.id: raise forms.ValidationError("An item may not supersede itself") if not user_can_edit(self.user, item): raise forms.ValidationError( "You cannot supersede with an item that you do not have permission to edit" ) return item
def test_editor_deleting_allowed_item(self): self.login_editor() before_count = self.wg1.items.count() self.assertEqual(self.wg1.items.count(), 1) response = self.client.get( reverse("admin:%s_%s_delete" % (self.itemType._meta.app_label, self.itemType._meta.model_name), args=[self.item1.pk])) self.assertResponseStatusCodeEqual(response, 200) response = self.client.post( reverse("admin:%s_%s_delete" % (self.itemType._meta.app_label, self.itemType._meta.model_name), args=[self.item1.pk]), {'post': 'yes'}) self.assertRedirects( response, reverse("admin:%s_%s_changelist" % (self.itemType._meta.app_label, self.itemType._meta.model_name))) self.assertEqual(self.wg1.items.count(), before_count - 1) self.item1 = self.itemType.objects.create(name="OC1", workgroup=self.wg1, **self.create_defaults) self.assertEqual(self.wg1.items.count(), 1) before_count = self.wg1.items.count() review = models.ReviewRequest.objects.create( requester=self.su, registration_authority=self.ra, state=self.ra.public_state, registration_date=datetime.date(2010, 1, 1)) review.concepts.add(self.item1) old_count = self.item1.statuses.count() self.ra.register(self.item1, models.STATES.standard, self.registrar) self.assertTrue(self.item1.statuses.count() == old_count + 1) self.item1 = self.itemType.objects.get( pk=self.item1.pk) # Dang DB cache self.assertTrue(self.item1.is_registered) self.assertTrue(self.item1.is_locked()) self.assertFalse(perms.user_can_edit(self.editor, self.item1)) before_count = self.wg1.items.count() response = self.client.get( reverse("admin:%s_%s_delete" % (self.itemType._meta.app_label, self.itemType._meta.model_name), args=[self.item1.pk])) self.assertResponseStatusCodeEqual(response, 404) self.assertEqual(self.wg1.items.count(), before_count) response = self.client.post( reverse("admin:%s_%s_delete" % (self.itemType._meta.app_label, self.itemType._meta.model_name), args=[self.item1.pk]), {'post': 'yes'}) self.assertResponseStatusCodeEqual(response, 404) self.assertEqual(self.wg1.items.count(), before_count)
def test_can_edit_cache(self): self.assertTrue(perms.user_can_edit(self.submitter,self.item)) self.item.definition = "edit name, then quickly check permission" self.item.save() self.assertTrue(perms.user_can_edit(self.submitter,self.item)) self.item.definition = "edit name, then wait 30 secs for 'recently edited to expire'" self.item.save() sleep(models.VERY_RECENTLY_SECONDS+2) self.assertTrue(perms.user_can_edit(self.submitter,self.item)) # register then immediately check the permissions to make sure the cache is ignored # technically we haven't edited the item yet, although ``concept.recache_states`` will be called. reg,c = models.Status.objects.get_or_create( concept=self.item, registrationAuthority=self.ra, registrationDate = datetime.date(2009,04,28), state = models.STATES.standard ) self.assertFalse(perms.user_can_edit(self.submitter,self.item))
def test_object_submitter_can_edit(self): registrar = get_user_model().objects.create_user( '*****@*****.**', 'registrar') self.ra.registrars.add(registrar) # make editor for wg1 wg1 = models.Workgroup.objects.create(name="Test WG 1") e1 = get_user_model().objects.create_user('*****@*****.**', 'editor1') wg1.giveRoleToUser('submitter', e1) # make editor for wg2 wg2 = models.Workgroup.objects.create(name="Test WG 2") e2 = get_user_model().objects.create_user('*****@*****.**', 'editor2') wg2.giveRoleToUser('submitter', e2) #RAFIX wg1.registrationAuthorities.add(self.ra) #RAFIX wg2.registrationAuthorities.add(self.ra) # ensure object is in wg1 self.item.workgroup = wg1 self.item.save() # test editor 1 can edit, editor 2 cannot self.assertEqual(perms.user_can_edit(e1, self.item), True) self.assertEqual(perms.user_can_edit(e2, self.item), False) # move Object Class to wg2 self.item.workgroup = wg2 self.item.save() # test editor 2 can edit, editor 1 cannot self.assertEqual(perms.user_can_edit(e2, self.item), True) self.assertEqual(perms.user_can_edit(e1, self.item), False) # self.ra.register(self.item,self.ra.locked_state,registrar,timezone.now(),) models.Status.objects.create(concept=self.item, registrationAuthority=self.ra, registrationDate=timezone.now(), state=self.ra.locked_state) # Editor 2 can no longer edit. Neither can Editor 1 self.assertEqual(perms.user_can_edit(e2, self.item), False) self.assertEqual(perms.user_can_view(e1, self.item), False)
def test_object_submitter_can_edit(self): registrar = User.objects.create_user("registrar", "", "registrar") self.ra.registrars.add(registrar) # make editor for wg1 wg1 = models.Workgroup.objects.create(name="Test WG 1") e1 = User.objects.create_user("editor1", "", "editor1") wg1.giveRoleToUser("submitter", e1) # make editor for wg2 wg2 = models.Workgroup.objects.create(name="Test WG 2") e2 = User.objects.create_user("editor2", "", "editor2") wg2.giveRoleToUser("submitter", e2) wg1.registrationAuthorities.add(self.ra) wg2.registrationAuthorities.add(self.ra) # ensure object is in wg1 self.item.workgroup = wg1 self.item.save() # test editor 1 can edit, editor 2 cannot self.assertEqual(perms.user_can_edit(e1, self.item), True) self.assertEqual(perms.user_can_edit(e2, self.item), False) # move Object Class to wg2 self.item.workgroup = wg2 self.item.save() # test editor 2 can edit, editor 1 cannot self.assertEqual(perms.user_can_edit(e2, self.item), True) self.assertEqual(perms.user_can_edit(e1, self.item), False) # self.ra.register(self.item,self.ra.locked_state,registrar,timezone.now(),) s = models.Status.objects.create( concept=self.item, registrationAuthority=self.ra, registrationDate=timezone.now(), state=self.ra.locked_state, ) # Editor 2 can no longer edit. Neither can Editor 1 self.assertEqual(perms.user_can_edit(e2, self.item), False) self.assertEqual(perms.user_can_view(e1, self.item), False)
def clean_olderItems(self): olderItems = self.cleaned_data['olderItems'] if self.item in olderItems: raise forms.ValidationError("An item may not supersede itself") for i in olderItems: if not user_can_edit(self.user, i): raise forms.ValidationError( "You cannot supersede an item that you do not have permission to edit" ) return olderItems
def valuedomain_value_edit(request, iid, value_type): item = get_object_or_404(MDR.ValueDomain, pk=iid).item if not user_can_edit(request.user, item): if request.user.is_anonymous(): return redirect(reverse('friendly_login') + '?next=%s' % request.path) else: raise PermissionDenied value_model = { 'permissible': MDR.PermissibleValue, 'supplementary': MDR.SupplementaryValue }.get(value_type, None) if not value_model: raise Http404 num_values = value_model.objects.filter(valueDomain=item.id).count() if num_values > 0: extra = 0 else: extra = 1 ValuesFormSet = modelformset_factory( value_model, can_delete=True, # dont need can_order is we have an order field fields=('order', 'value', 'meaning'), extra=extra ) if request.method == 'POST': formset = ValuesFormSet(request.POST, request.FILES) if formset.is_valid(): with transaction.atomic(), reversion.revisions.create_revision(): item.save() # do this to ensure we are saving reversion records for the value domain, not just the values formset.save(commit=False) for form in formset.forms: if form['value'].value() == '' and form['meaning'].value() == '': continue # Skip over completely blank entries. if form['id'].value() not in [deleted_record['id'].value() for deleted_record in formset.deleted_forms]: value = form.save(commit=False) # Don't immediately save, we need to attach the value domain value.valueDomain = item value.save() for obj in formset.deleted_objects: obj.delete() # formset.save(commit=True) reversion.revisions.set_user(request.user) reversion.revisions.set_comment(construct_change_message(request, None, [formset])) return redirect(reverse("aristotle_mdr:item", args=[item.id])) else: formset = ValuesFormSet( queryset=value_model.objects.filter(valueDomain=item.id), initial=[{'order': num_values, 'value': '', 'meaning': ''}] ) return render( request, "aristotle_mdr/actions/edit_value_domain_values.html", {'item': item, 'formset': formset, 'value_type': value_type, 'value_model': value_model} )
def test_object_submitter_can_edit(self): # set up ra = models.RegistrationAuthority.objects.create(name="Test RA") registrar = User.objects.create_user('registrar','','registrar') ra.registrars.add(registrar) # make editor for wg1 wg1 = models.Workgroup.objects.create(name="Test WG 1") e1 = User.objects.create_user('editor1','','editor1') wg1.giveRoleToUser('submitter',e1) # make editor for wg2 wg2 = models.Workgroup.objects.create(name="Test WG 2") e2 = User.objects.create_user('editor2','','editor2') wg2.giveRoleToUser('submitter',e2) # ensure object is in wg1 self.item.workgroup = wg1 self.item.save() # test editor 1 can edit, editor 2 cannot self.assertEqual(perms.user_can_edit(e1,self.item),True) self.assertEqual(perms.user_can_edit(e2,self.item),False) # move Object Class to wg2 self.item.workgroup = wg2 self.item.save() # test editor 2 can edit, editor 1 cannot self.assertEqual(perms.user_can_edit(e2,self.item),True) self.assertEqual(perms.user_can_edit(e1,self.item),False) #ra.register(self.item,ra.locked_state,registrar,timezone.now(),) s = models.Status.objects.create( concept=self.item, registrationAuthority=ra, registrationDate=timezone.now(), state=ra.locked_state ) # Editor 2 can no longer edit. Neither can Editor 1 self.assertEqual(perms.user_can_edit(e2,self.item),False) self.assertEqual(perms.user_can_view(e1,self.item),False)
def has_object_permission(self, request, view, obj): # Safe methods are GET, HEAD and OPTIONS if request.method in SAFE_METHODS: return perms.user_can_view(request.user, obj) elif request.method in ['PUT', 'PATCH']: return perms.user_can_edit(request.user, obj) elif request.method == 'DELETE': return obj.can_delete(request.user) return False
def dispatch(self, request, *args, **kwargs): pk = self.kwargs[self.lookup_url_kwarg] # Get item self.item = get_object_or_404(_concept, pk=pk).item if not user_can_edit(self.request.user, self.item): raise PermissionDenied() # Get associated versions versions = self.get_versions(self.item, self.request.user) self.version_ids = [version.pk for version in versions] return super().dispatch(request, *args, **kwargs)
def has_change_permission(self, request,obj=None): if obj is None: if request.GET.get('t',None) == "registrygroup_ptr": return True else: return True in (request.user.has_perm('aristotle_mdr.admin_in_{name}'.format(name=w.name)) for w in request.user.profile.workgroups.all() ) elif perms.user_can_edit(request.user,obj): return True else: return super(WorkgroupAdmin, self).has_change_permission(request,obj=None)
def dispatch(self, request, *args, **kwargs): if request.user.is_anonymous: return redirect(reverse('friendly_login') + '?next=%s' % request.path) if not request.user.has_perm('aristotle_mdr_links.add_link'): raise PermissionDenied self.root_item = get_object_or_404(MDR._concept, id=kwargs['iid']) if not user_can_edit(self.request.user, self.root_item): raise PermissionDenied return super().dispatch(request, *args, **kwargs)
def has_change_permission(self, request, obj=None): if obj is None: if request.GET.get('t', None) == "registrygroup_ptr": return True else: return True in (request.user.has_perm( 'aristotle_mdr.admin_in_{name}'.format(name=w.name)) for w in request.user.profile.workgroups.all()) elif perms.user_can_edit(request.user, obj): return True else: return super().has_change_permission(request, obj=None)
def dispatch(self, request, *args, **kwargs): if not self.item: self.item = get_object_or_404( MDR._concept, pk=self.kwargs['iid'] ).item self.model = self.item.__class__ if not user_can_edit(self.request.user, self.item): if request.user.is_anonymous(): return redirect(reverse('friendly_login') + '?next=%s' % request.path) else: raise PermissionDenied return super(PermissionFormView, self).dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): if request.user.is_anonymous(): return redirect(reverse('friendly_login') + '?next=%s' % request.path) if not request.user.has_perm('aristotle_mdr_links.add_link'): raise PermissionDenied self.root_item = get_object_or_404(MDR._concept, id=kwargs['iid']) if not user_can_edit(self.request.user, self.root_item): raise PermissionDenied return super().dispatch(request, *args, **kwargs)
def editInclusionDetails(request, dss_id, inc_type, cluster_id): dss = get_object_or_404(aristotle_dse.models.DataSetSpecification, id=dss_id) if inc_type not in ['cluster', 'data_element']: raise Http404 item = get_object_or_404(aristotle_dse.models.DataSetSpecification, pk=dss_id) if not user_can_edit(request.user, item): if request.user.is_anonymous(): return redirect(reverse('friendly_login') + '?next=%s' % request.path) else: raise PermissionDenied item_type, field_name = { 'cluster': (aristotle_dse.models.DataSetSpecification, 'child'), 'data_element': (aristotle.models.DataElement, 'data_element'), }.get(inc_type) cluster=get_object_or_404(item_type, id=cluster_id) if not (user_can_edit(request.user, dss) and user_can_view(request.user, cluster_id)): raise PermissionDenied inclusion = get_object_or_404(aristotle_dse.models.DSSClusterInclusion, child=cluster, dss=dss) if request.method == 'POST': form = forms.EditClusterInclusionForm(request.POST, instance=inclusion) # , user=request.user) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("aristotle_mdr:item", args=[dss.id])) else: form = forms.EditClusterInclusionForm(instance=inclusion) # , user=request.user) return render( request, "aristotle_dse/actions/edit_inclusion.html", { "item": inclusion, "form": form, "include_type": inc_type, } )
def test_managersCanEditWorkgroups(self): wg = models.Workgroup.objects.create(name="Test WG 1") user1 = User.objects.create_user('manager','','manager') user2 = User.objects.create_user('editor','','editor') wg.addUser(user1) wg.addUser(user2) wg.giveRoleToUser("Manager",user1) wg.giveRoleToUser("Viewer",user2) # Caching issue, refresh from DB with correct permissions user1 = User.objects.get(pk=user1.pk) user2 = User.objects.get(pk=user2.pk) self.assertTrue(perms.user_in_workgroup(user1,wg)) self.assertTrue(perms.user_in_workgroup(user2,wg)) self.assertTrue(perms.user_can_edit(user1,wg)) self.assertFalse(perms.user_can_edit(user2,wg)) wg.removeUser(user1) wg.removeUser(user2) # Caching issue, refresh from DB with correct permissions user1 = User.objects.get(pk=user1.pk) user2 = User.objects.get(pk=user2.pk) self.assertFalse(perms.user_can_edit(user1,wg)) self.assertFalse(perms.user_can_edit(user2,wg))
def dispatch(self, request, *args, **kwargs): if not self.item: self.item = get_object_or_404(MDR._concept, pk=self.kwargs['iid']).item self.model = self.item.__class__ if not user_can_edit(self.request.user, self.item): if request.user.is_anonymous(): return redirect( reverse('friendly_login') + '?next=%s' % request.path) else: raise PermissionDenied return super(PermissionFormView, self).dispatch(request, *args, **kwargs)
def render_if_condition_met(condition,objtype,request,iid=None,subpage=None): if iid is None: app_name = objtype._meta.app_label return redirect(reverse("%s:dynamic"%app_name,args=["".join(objtype._meta.verbose_name.title().lower().split())])) item = get_object_or_404(objtype,pk=iid).item if not condition(request.user, item): if request.user.is_anonymous(): return redirect('/accounts/login?next=%s' % request.path) else: raise PermissionDenied # We add a user_can_edit flag in addition to others as we have odd rules around who can edit objects. isFavourite = request.user.is_authenticated () and request.user.profile.isFavourite(item.id) """ if subpage=="related": from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger related_items = item.relatedItems(request.user) paginator = Paginator(related_items, PAGES_PER_RELATED_ITEM) page = request.GET.get('page') try: related_items = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. related_items = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. related_items = paginator.page(paginator.num_pages) return render(request,"aristotle_mdr/relatedItems.html", {'item':item, 'relatedItems':related_items,} ) else: Lets disable the related page for the time being Only a handful of Object classes will be impacted. """ from reversion.revisions import default_revision_manager last_edit = default_revision_manager.get_for_object_reference( item.__class__, item.pk, ).first() return render(request,item.template, {'item':item, 'user_can_edit':user_can_edit(request.user,item), 'view':request.GET.get('view','').lower(), 'isFavourite': isFavourite, 'last_edit': last_edit } )
def test_editor_deleting_allowed_item(self): self.login_editor() # make some items before_count = self.wg1.items.count() self.assertEqual(self.wg1.items.count(), 1) response = self.client.get( reverse("admin:%s_%s_delete" % (self.itemType._meta.app_label, self.itemType._meta.model_name), args=[self.item1.pk])) self.assertResponseStatusCodeEqual(response, 200) response = self.client.post( reverse("admin:%s_%s_delete" % (self.itemType._meta.app_label, self.itemType._meta.model_name), args=[self.item1.pk]), {'post': 'yes'}) self.assertRedirects( response, reverse("admin:%s_%s_changelist" % (self.itemType._meta.app_label, self.itemType._meta.model_name))) self.assertEqual(self.wg1.items.count(), before_count - 1) self.item1 = self.itemType.objects.create(name="OC1", workgroup=self.wg1, readyToReview=True, **self.create_defaults) self.assertEqual(self.wg1.items.count(), 1) before_count = self.wg1.items.count() self.ra.register(self.item1, models.STATES.standard, self.registrar) self.item1 = self.itemType.objects.get( pk=self.item1.pk) # Dang DB cache self.assertTrue(self.item1.is_registered) self.assertTrue(self.item1.is_locked()) self.assertFalse(perms.user_can_edit(self.editor, self.item1)) before_count = self.wg1.items.count() response = self.client.get( reverse("admin:%s_%s_delete" % (self.itemType._meta.app_label, self.itemType._meta.model_name), args=[self.item1.pk])) self.assertResponseStatusCodeEqual(response, 404) self.assertEqual(self.wg1.items.count(), before_count) response = self.client.post( reverse("admin:%s_%s_delete" % (self.itemType._meta.app_label, self.itemType._meta.model_name), args=[self.item1.pk]), {'post': 'yes'}) self.assertResponseStatusCodeEqual(response, 404) self.assertEqual(self.wg1.items.count(), before_count)
def test_managersCanEditWorkgroups(self): wg = models.Workgroup.objects.create(name="Test WG 1") user1 = get_user_model().objects.create_user('*****@*****.**','manager') user2 = get_user_model().objects.create_user('*****@*****.**','viewer') wg.managers.add(user1) wg.viewers.add(user2) wg.save() wg = models.Workgroup.objects.get(pk=wg.id) self.assertTrue(perms.user_in_workgroup(user1,wg)) self.assertTrue(perms.user_in_workgroup(user2,wg)) self.assertTrue(perms.user_can_view(user2,wg)) self.assertTrue(perms.user_can_view(user1,wg)) self.assertTrue(perms.user_can_edit(user1,wg)) self.assertFalse(perms.user_can_edit(user2,wg)) wg.removeUser(user1) wg.removeUser(user2) # Caching issue, refresh from DB with correct permissions user1 = get_user_model().objects.get(pk=user1.pk) user2 = get_user_model().objects.get(pk=user2.pk) self.assertFalse(perms.user_can_edit(user1,wg)) self.assertFalse(perms.user_can_edit(user2,wg))
def perform_deletion(self): de_id = self.kwargs['de_id'] dss_id = self.kwargs['dss_id'] de = get_object_or_404(aristotle.models.DataElement, id=de_id) dss = get_object_or_404(aristotle_dse.models.DataSetSpecification, id=dss_id) if user_can_view(self.request.user, de) and user_can_edit(self.request.user, dss): dss.dssdeinclusion_set.filter(data_element=de).delete() messages.success( self.request, _('The Data Element "%(de_name)s" was removed from the dataset "%(dss_name)s".') % { "de_name": de.name, "dss_name": dss.name } ) else: raise PermissionDenied
def perform_deletion(self): cluster_id = self.kwargs['cluster_id'] dss_id = self.kwargs['dss_id'] cluster = get_object_or_404(aristotle_dse.models.DataSetSpecification, id=cluster_id) dss = get_object_or_404(aristotle_dse.models.DataSetSpecification, id=dss_id) if user_can_view(self.request.user, cluster) and user_can_edit(self.request.user, dss): dss.dssclusterinclusion_set.filter(child=cluster).delete() messages.success( self.request, _('The cluster "%(cl_name)s" was removed from the dataset "%(dss_name)s".') % { "cl_name": cluster.name, "dss_name": dss.name } ) else: raise PermissionDenied
def submitter_user_can_use_value_edit_page(self,value_type): self.login_editor() self.loggedin_user_can_use_value_page(value_type,self.item1,200) self.loggedin_user_can_use_value_page(value_type,self.item2,403) self.loggedin_user_can_use_value_page(value_type,self.item3,200) # Invalid value domain types are caught in the URL runner. This test isn't required yet. #response = self.client.get(reverse('aristotle:valueDomain_edit_values',args=[self.item1.id,'accidentally'])) # a fake value domain type #self.assertTrue(response.status_code,404) data = {} num_vals = getattr(self.item1,value_type+"Values").count() i=0 for i,v in enumerate(getattr(self.item1,value_type+"Values").all()): data.update({"form-%d-id"%i: v.pk, "form-%d-order"%i : v.order, "form-%d-value"%i : v.value, "form-%d-meaning"%i : v.meaning+" -updated"}) data.update({"form-%d-DELETE"%i: 'checked', "form-%d-meaning"%i : v.meaning+" - deleted"}) # delete the last one. # now add a new one i=i+1 data.update({"form-%d-order"%i : i, "form-%d-value"%i : 100, "form-%d-meaning"%i : "new value -updated"}) data.update({ "form-TOTAL_FORMS":num_vals+1, "form-INITIAL_FORMS": num_vals, "form-MAX_NUM_FORMS":1000, }) response = self.client.post(reverse('aristotle:valueDomain_edit_values',args=[self.item1.id,value_type]),data) self.item1 = models.ValueDomain.objects.get(pk=self.item1.pk) self.assertTrue(num_vals == getattr(self.item1,value_type+"Values").count()) new_value_seen = False for v in getattr(self.item1,value_type+"Values").all(): self.assertTrue('updated' in v.meaning) # This will fail if the deleted item isn't deleted if v.value == '100': new_value_seen = True self.assertTrue(new_value_seen) # Item is now locked, submitter is no longer able to edit models.Status.objects.create( concept=self.item1, registrationAuthority=self.ra, registrationDate=timezone.now(), state=self.ra.locked_state ) self.item1 = models.ValueDomain.objects.get(pk=self.item1.pk) self.assertTrue(self.item1.is_locked()) self.assertFalse(perms.user_can_edit(self.editor,self.item1)) self.loggedin_user_can_use_value_page(value_type,self.item1,403)
def can_edit(item,user): """ A filter that acts as a wrapper around ``aristotle_mdr.perms.user_can_edit``. Returns true if the user has permission to edit the item, otherwise it returns False. If calling ``user_can_edit`` throws an exception it safely returns False. For example:: {% if myItem|can_edit:request.user %} {{ item }} {% endif %} """ try: return perms.user_can_edit(user,item) except: return False