Esempio n. 1
0
 def test_fallback_to_anonymous_user(self):
     repo = Repository(owner=self._human_a, name='Node isnt web scale')
     repo.save()
     self.assertTrue(self._human_a.has_perm('read', repo))
     self.assertFalse(self._human_b.has_perm('read', repo))
     assign('read', get_anonymous_user(), repo)
     self.assertTrue(self._human_b.has_perm('read', repo))
Esempio n. 2
0
 def save(self):
     super(GroupForm, self).save()
     user = db.User.objects.get(username=self.data['user'])
     assign('change_group', user, self.instance)
     assign('delete_group', user, self.instance)
     self.instance.user_set.add(user)
     return self.instance
Esempio n. 3
0
 def test_remove_perm(self):
     assign('contenttypes.change_contenttype', self.user, self.ctype)
     self.assertTrue(self.user.has_perm('contenttypes.change_contenttype',
         self.ctype))
     remove_perm('contenttypes.change_contenttype', self.user, self.ctype)
     self.assertFalse(self.user.has_perm('contenttypes.change_contenttype',
         self.ctype))
Esempio n. 4
0
    def test_create_minimal_nodeset(self):
        '''Test adding a new NodeSet with required fields only

        '''
        dataset = DataSet.objects.create()
        InvestigationLink.objects.create(data_set=dataset,
                                         investigation=self.investigation)
        assign("read_%s" % dataset._meta.module_name, self.user, dataset)
        nodeset_data = {
            'name': 'nodeset1',
            'study': make_api_uri('study', self.study.uuid),
            'assay': make_api_uri('assay', self.assay.uuid),
            'is_implicit': True
        }
        nodeset_uri = make_api_uri('nodeset')

        self.assertEqual(NodeSet.objects.count(), 0)
        response = self.api_client.post(nodeset_uri,
                                        format='json',
                                        data=nodeset_data,
                                        authentication=self.get_credentials())
        self.assertHttpCreated(response)
        self.assertEqual(NodeSet.objects.count(), 1)
        nodeset = NodeSet.objects.get(name=nodeset_data['name'])
        self.assertEqual(nodeset.get_owner(), self.user)
Esempio n. 5
0
 def test_perms_single(self):
     perm = 'contenttypes.change_contenttype'
     assign(perm, self.group1, self.obj1)
     self.assertEqual(
         set(get_objects_for_group(self.group1, perm)),
         set(get_objects_for_group(self.group1, [perm]))
     )
Esempio n. 6
0
    def test_group_remove_perm(self):
        # assign perm first
        assign("change_keycard", self.group, self.keycard)
        remove_perm("change_keycard", self.group, self.keycard)

        check = ObjectPermissionChecker(self.group)
        self.assertFalse(check.has_perm("change_keycard", self.keycard))
Esempio n. 7
0
    def test_klass_as_model(self):
        assign('contenttypes.change_contenttype', self.group1, self.obj1)

        objects = get_objects_for_group(self.group1,
                                        ['contenttypes.change_contenttype'],
                                        ContentType)
        self.assertEqual([obj.name for obj in objects], [self.obj1.name])
Esempio n. 8
0
 def save(self, *args, **kwargs):
     """
     Give the user proper permissions so django guardian can check them
     """
     from guardian.shortcuts import assign
     super(TeamMember, self).save(*args, **kwargs)
     assign(PERMISSION_NAMES[self.permission - 1], self.user, self.team)
Esempio n. 9
0
    def test_attach_perms(self):
        self.user1.groups.add(self.group1)
        self.user2.groups.add(self.group2)
        self.user3.groups.add(self.group3)
        assign("change_contenttype", self.group1, self.obj1)
        assign("change_contenttype", self.group2, self.obj1)
        assign("delete_contenttype", self.group3, self.obj2)
        assign("delete_contenttype", self.user2, self.obj1)
        assign("change_contenttype", self.user3, self.obj2)

        # Check contenttype1
        result = get_users_with_perms(self.obj1, attach_perms=True)
        expected = {
            self.user1: ["change_contenttype"],
            self.user2: ["change_contenttype", "delete_contenttype"],
        }
        self.assertEqual(result.keys(), expected.keys())
        for key, perms in result.iteritems():
            self.assertEqual(set(perms), set(expected[key]))

        # Check contenttype2
        result = get_users_with_perms(self.obj2, attach_perms=True)
        expected = {
            self.user3: ["change_contenttype", "delete_contenttype"],
        }
        self.assertEqual(result.keys(), expected.keys())
        for key, perms in result.iteritems():
            self.assertEqual(set(perms), set(expected[key]))
Esempio n. 10
0
    def test_klass_as_model(self):
        assign('contenttypes.change_contenttype', self.user, self.ctype)

        objects = get_objects_for_user(self.user,
                                       ['contenttypes.change_contenttype'],
                                       ContentType)
        self.assertEqual([obj.name for obj in objects], [self.ctype.name])
Esempio n. 11
0
    def test_group_remove_perm(self):
        # assign perm first
        assign("change_contenttype", self.group, self.ctype)
        remove_perm("change_contenttype", self.group, self.ctype)

        check = ObjectPermissionChecker(self.group)
        self.assertFalse(check.has_perm("change_contenttype", self.ctype))
Esempio n. 12
0
 def test_author_only_set_once(self):
     path = reverse('publicweb_decision_create',
                    args=[self.bettysorg.slug, Decision.PROPOSAL_STATUS])
     post_dict = {
         'status': Decision.PROPOSAL_STATUS,
         'description': 'Lorem Ipsum'
     }
     response = self.client.post(path, post_dict)
     self.assertRedirects(
         response,
         reverse('publicweb_item_list',
                 args=[self.bettysorg.slug, 'proposal']))
     decision = Decision.objects.get(description='Lorem Ipsum')
     self.assertEqual(decision.author, self.user)
     self.user = self.login('charlie')
     #allow charlie to edit
     assign('edit_decisions_feedback', self.user, self.bettysorg)
     path = reverse('publicweb_decision_update', args=[decision.id])
     post_dict = {
         'status': Decision.PROPOSAL_STATUS,
         'description': 'ullamcorper nunc'
     }
     response = self.client.post(path, post_dict)
     self.assertRedirects(
         response,
         reverse('publicweb_item_list',
                 args=[self.bettysorg.slug, 'proposal']))
     decision = Decision.objects.get(description='ullamcorper nunc')
     self.assertNotEqual(decision.author, self.user)
Esempio n. 13
0
 def test_with_perm_get_survey_by_uuid(self):
     self._create_user_and_login('alice', 'alice')
     assign('view_xform', self.user, self.xform)
     response = self.client.get(self.url)
     self.assertEquals(response.status_code, 302)
     self.assertEquals(self.base_url + self.survey_url,
                       response['Location'])
Esempio n. 14
0
    def check_permissions(self):
        """
        Checks that all permissions are set correctly for the users.

        :return: A set of users whose permissions was wrong.

        """
        changed_users = set()
        for user in User.objects.all():
            if not user.username == 'AnonymousUser':
                all_permissions = get_perms(
                    user, user.get_profile()) + get_perms(user, user)

                for model, perms in PERMISSIONS.items():
                    if model == 'profile':
                        perm_object = user.get_profile()
                    else:
                        perm_object = user

                    for perm in perms:
                        if perm not in all_permissions:
                            assign(perm, user, perm_object)
                            changed_users.add(user)

        return changed_users
Esempio n. 15
0
    def test_group_assing(self):
        assign("change_contenttype", self.group, self.ctype)
        assign("delete_contenttype", self.group, self.ctype)

        check = ObjectPermissionChecker(self.group)
        self.assertTrue(check.has_perm("change_contenttype", self.ctype))
        self.assertTrue(check.has_perm("delete_contenttype", self.ctype))
Esempio n. 16
0
    def test_emails_contain_extra_header_info(self):
        users_orgs = Organization.active.get_for_user(self.user)
        self.assertGreaterEqual(len(users_orgs), 2)
        decision = self.make_decision(organization=users_orgs[0])
        outbox = getattr(mail, 'outbox')
        self.assertTrue(outbox)
        self.assertTrue(outbox[0].extra_headers)
        self.assertEqual(outbox[0].extra_headers['Message-ID'], decision.get_message_id())
        mail.outbox = []

        decision = self.update_decision_through_browser(decision.id)
        outbox = getattr(mail, 'outbox')
        self.assertTrue(outbox)
        self.assertTrue(outbox[0].extra_headers)
        self.assertEqual(outbox[0].extra_headers['Message-ID'], decision.get_message_id())
        mail.outbox = []

        feedback = self.create_feedback_through_browser(decision.id)
        outbox = getattr(mail, 'outbox')
        self.assertTrue(outbox)
        self.assertTrue(outbox[0].extra_headers)
        self.assertEqual(outbox[0].extra_headers['Message-ID'], feedback.get_message_id())
        self.assertEqual(outbox[0].extra_headers['In-Reply-To'], feedback.decision.get_message_id())
        mail.outbox = []
        
        self.login('charlie')
        assign('edit_decisions_feedback', self.user, self.bettysorg)        
        feedback = self.update_feedback_through_browser(feedback.id)
        outbox = getattr(mail, 'outbox')
        self.assertTrue(outbox)
        self.assertTrue(outbox[0].extra_headers)
        self.assertEqual(outbox[0].extra_headers['Message-ID'], feedback.get_message_id())
        self.assertEqual(outbox[0].extra_headers['In-Reply-To'], feedback.decision.get_message_id())
Esempio n. 17
0
 def save(self, commit=True):
     self.instance = super(CustomOrganizationUserAddForm, self).save(commit=commit)
     if self.cleaned_data['is_editor']:
         assign('edit_decisions_feedback', self.instance.user, self.instance.organization)
     else:
         remove_perm('edit_decisions_feedback', self.instance.user, self.instance.organization)
     return self.instance
Esempio n. 18
0
 def test_without_group_users_no_result(self):
     self.user1.groups.add(self.group1)
     assign("change_contenttype", self.group1, self.obj1)
     result = get_users_with_perms(self.obj1, attach_perms=True,
             with_group_users=False)
     expected = {}
     self.assertEqual(result, expected)
Esempio n. 19
0
    def test_clean_perms(self):

        # assign obj perms
        target_perms = {
            self.target_user1: ["change_user"],
            self.target_group1: ["delete_group"],
            self.target_obj1: ["change_contenttype", "delete_contenttype"],
            self.target_obj2: ["change_contenttype"],
        }
        obj_perms_count = sum([len(val) for key, val in target_perms.items()])
        for target, perms in target_perms.items():
            target.__old_pk = target.pk  # Store pkeys
            for perm in perms:
                assign(perm, self.user, target)

        # Remove targets
        for target, perms in target_perms.items():
            target.delete()

        # Clean orphans
        removed = clean_orphan_obj_perms()
        self.assertEqual(removed, obj_perms_count)

        # Recreate targets and check if user has no permissions
        for target, perms in target_perms.items():
            target.pk = target.__old_pk
            target.save()
            for perm in perms:
                self.assertFalse(self.user.has_perm(perm, target))
Esempio n. 20
0
    def test_image_operations_as_authorised_users(self):
        # create a campaign & deployment that ONLY bill can see
        bills_campaign = mommy.make_one("catamidb.Campaign", id=3, short_name="cp__1")
        bills_deployment = mommy.make_recipe("catamidb.Deployment3", id=3, campaign=bills_campaign)
        bills_image = mommy.make_recipe("catamidb.Image3", id=3, deployment=bills_deployment)
        assign("view_campaign", self.user_bill, bills_campaign)

        # check that bill can see via the API
        response = self.bill_api_client.get(self.image_url, format="json")
        self.assertValidJSONResponse(response)
        self.assertEqual(len(self.deserialize(response)["objects"]), 3)

        # check that bill can get to the object itself
        response = self.bill_api_client.get(self.image_url + "3/", format="json")
        self.assertValidJSONResponse(response)

        # check that bob can not see - now we know tastypie API has correct
        # permission validation
        response = self.bob_api_client.get(self.image_url, format="json")
        self.assertValidJSONResponse(response)
        self.assertEqual(len(self.deserialize(response)["objects"]), 2)

        # check bob can NOT get to the hidden object
        response = self.bob_api_client.get(self.image_url + "3/", format="json")
        self.assertHttpUnauthorized(response)

        # check that anonymous can see public ones as well
        response = self.anon_api_client.get(self.image_url, format="json")
        self.assertValidJSONResponse(response)
        self.assertEqual(len(self.deserialize(response)["objects"]), 2)

        # check anonymous can NOT get to the hidden object
        response = self.anon_api_client.get(self.image_url + "3/", format="json")
        self.assertHttpUnauthorized(response)
Esempio n. 21
0
    def test_clean_perms_command(self):
        """
        Same test as the one above but rather function directly, we call
        management command instead.
        """

        # assign obj perms
        target_perms = {
            self.target_user1: ["change_user"],
            self.target_group1: ["delete_group"],
            self.target_obj1: ["change_contenttype", "delete_contenttype"],
            self.target_obj2: ["change_contenttype"],
        }
        for target, perms in target_perms.items():
            target.__old_pk = target.pk  # Store pkeys
            for perm in perms:
                assign(perm, self.user, target)

        # Remove targets
        for target, perms in target_perms.items():
            target.delete()

        # Clean orphans
        call_command("clean_orphan_obj_perms", verbosity=0)

        # Recreate targets and check if user has no permissions
        for target, perms in target_perms.items():
            target.pk = target.__old_pk
            target.save()
            for perm in perms:
                self.assertFalse(self.user.has_perm(perm, target))
Esempio n. 22
0
 def test_disallow_map_if_user_permission_revoked(self):
     self._create_user_and_login('alice')
     assign('change_xform', self.user, self.xform)
     response = self.client.get(self.url)
     remove_perm('change_xform', self.user, self.xform)
     response = self.client.get(self.url)
     self.assertEqual(response.status_code, 403)
Esempio n. 23
0
    def save(self, *args, **kw):
        #TODO: abort save if sent
        if self.pk is not None:
            orig = Request.objects.get(pk=self.pk)
            if orig.private != self.private:
                logger.info("request %s privacy changed to=%s from=%s" % (self.slug, self.private, orig.private))
                group, g_created = Group.objects.get_or_create(name='public')
                if self.private == True:
                    remove_perm(Request.get_permission_name('view'), group, self)
                    logger.info('request %s permissions changed: removed from public' % (self.slug))
                else:
                    assign(Request.get_permission_name('view'), group, self)
                    logger.info('request %s permissions changed: added to public' % (self.slug))
            if self.contacts is not None and self.contacts.count() > 0 and self.contacts.all()[0].get_related_agencies().count() > 0:
                self.agency = self.contacts.all()[0].get_related_agencies()[0]
                self.government = self.agency.government
            else:
                self.agency = None
                self.government = None
        else:
            self.status = 'I'
            #code = "LOOKUP:" + User.objects.make_random_password(length=64)
            code = '2016' + '_payroll_' + self.agency.name.replace(' ','') 

            #while Request.objects.filter(thread_lookup=code):
            #    code = User.objects.make_random_password(length=64)
            self.thread_lookup = code

        super(Request, self).save(*args, **kw)
Esempio n. 24
0
def assign_permission(new_groups, objects, perm):
    groups = Group.objects.all()
    for obj in objects:
        for group in groups:
            remove_perm(perm, group, obj)
        for new_group in new_groups:
            assign(perm, new_group, obj)
Esempio n. 25
0
def add_change_profile_perm(sender, instance, created, raw, using, **kwargs):
    """ Adds 'change_profile' permission to created user objects """
    if created:
        try:
            assign('change_profile', instance, instance.get_profile())
        except:
            pass  # Anonymous user
Esempio n. 26
0
    def test_get_nodeset_list_for_given_study_and_assay(self):
        '''Test retrieving a list of NodeSets for given study and assay.

        '''
        nodeset1 = NodeSet.objects.create(name='ns1',
                                          study=self.study,
                                          assay=self.assay,
                                          node_count=1,
                                          is_implicit=True,
                                          solr_query=simplejson.dumps(
                                              self.query))
        assign("read_%s" % nodeset1._meta.module_name, self.user, nodeset1)
        nodeset2 = NodeSet.objects.create(name='ns2',
                                          study=self.study2,
                                          assay=self.assay2,
                                          node_count=1,
                                          is_implicit=True,
                                          solr_query=simplejson.dumps(
                                              self.query))
        assign("read_%s" % nodeset2._meta.module_name, self.user2, nodeset2)

        response = self.api_client.get(self.nodeset_uri,
                                       format='json',
                                       authentication=self.get_credentials(),
                                       data={
                                           'study__uuid': self.study.uuid,
                                           'assay__uuid': self.assay.uuid
                                       })
        self.assertValidJSONResponse(response)
        data = self.deserialize(response)['objects']
        self.assertEqual(len(data), 1)
        self.assertEqual(data[0]['name'], nodeset1.name)
Esempio n. 27
0
 def test_inactive_user_blocked(self):
     t = Thing(name='Test thing')
     t.save()
     self.user.is_active = False
     self.user.save()
     assign('change_thing', self.user, t)
     self.assertFalse(self.user.has_perm('tests.change_thing', t))
Esempio n. 28
0
    def test_group_remove_perm(self):
        # assign perm first
        assign("change_flatpage", self.group, self.flatpage)
        remove_perm("change_flatpage", self.group, self.flatpage)

        check = ObjectPermissionChecker(self.group)
        self.assertFalse(check.has_perm("change_flatpage", self.flatpage))
Esempio n. 29
0
    def test_object_permissions_win_over_group(self):
        t = Thing(name='Test thing')
        t.save()

        perm = Permission.objects.get(codename="add_thing")
        self.group.permissions.add(perm)
        perm = Permission.objects.get(codename="change_thing")
        self.group.permissions.add(perm)
        perm = Permission.objects.get(codename="delete_thing")
        self.group.permissions.add(perm)
        self.user.save()

        self.assertTrue(self.user.has_perm('tests.change_thing'))
        self.assertTrue(self.user.has_perm('tests.add_thing'))
        self.assertTrue(self.user.has_perm('tests.delete_thing'))

        self.assertTrue(self.user.has_perm('tests.change_thing', t))
        self.assertTrue(self.user.has_perm('tests.add_thing', t))
        self.assertTrue(self.user.has_perm('tests.delete_thing', t))

        assign('change_thing', self.group, t)  # per-object permission

        self.assertTrue(self.user.has_perm('tests.change_thing', t))
        self.assertFalse(self.user.has_perm('tests.add_thing', t))
        self.assertFalse(self.user.has_perm('tests.delete_thing', t))
Esempio n. 30
0
def reqedit(request, reqid=None):
    '''
    controller for individual numerical requirement edit page
    '''
    
    req = get_object_or_404(NumericalRequirement, pk=reqid)  
    
    # get my urls
    urls = {}
    urls = getsiteurls(urls)
    urls = getexpurls(urls)    
          
    if request.method == 'POST': 
        cancel = request.POST.get('cancel', None)
        if cancel:
            urls['reqview']=reverse('pimms.apps.exp.views.reqview', args=(req.id, ))
            return HttpResponseRedirect(urls['reqview'])
        else:          
            reqform = RequirementForm(request.POST, instance=req)
            if reqform.is_valid():
                req = reqform.save(commit=False)
                req.author = request.user
                req.save()
                # assign permissions to access this requirement
                assign('manage_req', request.user, req)
                
                return HttpResponseRedirect(urls['reqlist']) # Redirect after POST
            else:
                return render_to_response('exp/reqedit.html', {'reqform': reqform, 'urls':urls}, context_instance=RequestContext(request))
    else:
        reqform = RequirementForm(instance=req) # An unbound form

    return render_to_response('exp/reqedit.html', {'reqform': reqform, 'urls':urls}, 
                                context_instance=RequestContext(request))
Esempio n. 31
0
def assign_user_to_page(page, user, can_add=False, can_change=False,
                        can_delete=False, can_change_advanced_settings=False,
                        can_publish=False, can_change_permissions=False,
                        can_view=False, grant_all=False, global_permission=False):
    """
    Assigns given user to page, and gives him requested permissions.

    See docs/extending_poser/api_reference.rst for more info
    """
    if grant_all and not global_permission:
        # shortcut to grant all permissions
        return assign_user_to_page(page, user, True, True, True, True,
                                   True, True, True)

    data = {
        'add_page': can_add,
        'change_page': can_change,
        'delete_page': can_delete,
        'change_advanced_settings_page': can_change_advanced_settings,
        'publish_page': can_publish,
        'change_permissions_page': can_change_permissions,
        'view_page': can_view,
    }
    for perm in data.iterkeys():
        if data[perm] is False:
            continue
        assign(perm, user, page)
Esempio n. 32
0
    def save(self, commit=True):
        """
        Saves granted permissions and removes those switched off.
        """
        member, project = self.membership.member, self.membership.project

        granted_perms = self.cleaned_data['permissions']
        logging.info("Granted perms: %s" % granted_perms)
        member_perms = get_perms(member, project)
        # Grant permissions
        for perm in granted_perms:
            if perm not in member_perms:
                assign(perm, member, project)
                self._message('info', _("Permission added: %s" % perm))
        # Remove permissions
        for perm in member_perms:
            if perm not in granted_perms:
                remove_perm(perm, member, project)
                # notify user if perm is still granted by member's groups
                groups_with_perm = member.groups.filter(
                    groupobjectpermission__permission__codename=perm)
                if groups_with_perm:
                    messages.warning(self.request, _("Permission %(perm)s is "
                        "still granted for %(user)s as following group(s) "
                        "has/have it: %(groups)s" % {
                            'perm': perm,
                            'user': member,
                            'groups': ', '.join(
                                (str(group) for group in groups_with_perm)
                            )
                        }))
                self._message('warning', _("Permission removed: %s" % perm))
Esempio n. 33
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
            }))
Esempio n. 34
0
 def save(self, commit=True):
     self.instance = super(CustomOrganizationUserAddForm, self).save(commit=commit)
     if self.cleaned_data["is_editor"]:
         assign("edit_decisions_feedback", self.instance.user, self.instance.organization)
     else:
         remove_perm("edit_decisions_feedback", self.instance.user, self.instance.organization)
     return self.instance
Esempio n. 35
0
def assign_forum_permissions(request, id, gid):
    if not request.user.is_superuser:
        return HttpResponseForbidden()

    obj = get_object_or_404(Forum, id=id)
    group = get_object_or_404(Group, id=gid)
    obj_permissions = get_perms_for_model(Forum).exclude(
        codename__in=['add_forum', 'can_views_forums'])

    ctype = ContentType.objects.get_for_model(obj)
    perms = []
    for group_perm in GroupObjectPermission.objects.filter(group=group,
                                                           content_type=ctype,
                                                           object_pk=obj.id):
        perms.append(group_perm.permission)
        #print perms
    PermissionsForm = get_permissions_form(obj_permissions.select_related(),
                                           initial=perms)
    if request.method == 'POST':
        form = PermissionsForm(request.POST)
        if form.is_valid():
            for perm in obj_permissions:
                remove_perm(perm.codename, group, obj)

            for perm in form.cleaned_data['perms']:
                assign(perm.codename, group, obj)

    else:
        form = PermissionsForm()

    return render(request, 'forum/frontend/edit_permissions.html', {
        'forum': obj,
        'group': group,
        'form': form,
    })
Esempio n. 36
0
    def test_attach_perms(self):
        self.user1.groups.add(self.group1)
        self.user2.groups.add(self.group2)
        self.user3.groups.add(self.group3)
        assign("change_contenttype", self.group1, self.obj1)
        assign("change_contenttype", self.group2, self.obj1)
        assign("delete_contenttype", self.group3, self.obj2)
        assign("delete_contenttype", self.user2, self.obj1)
        assign("change_contenttype", self.user3, self.obj2)

        # Check contenttype1
        result = get_users_with_perms(self.obj1, attach_perms=True)
        expected = {
            self.user1: ["change_contenttype"],
            self.user2: ["change_contenttype", "delete_contenttype"],
        }
        self.assertEqual(result.keys(), expected.keys())
        for key, perms in result.iteritems():
            self.assertEqual(set(perms), set(expected[key]))

        # Check contenttype2
        result = get_users_with_perms(self.obj2, attach_perms=True)
        expected = {
            self.user3: ["change_contenttype", "delete_contenttype"],
        }
        self.assertEqual(result.keys(), expected.keys())
        for key, perms in result.iteritems():
            self.assertEqual(set(perms), set(expected[key]))
Esempio n. 37
0
def auto_create_project_group(instance, created, **kwargs):
    name = PROJECT_GROUP_TEMPLATE.format(instance.name)
    group, created = Group.objects.get_or_create(name=name)

    # TODO change this to queue up an email rather than doing it in process..
    if created:
        assign('view_project', group, instance)

        try:
            kwargs = {
                'subject':
                '{0}Project "{1}" Created'.format(
                    settings.EMAIL_SUBJECT_PREFIX, name),
                'message':
                'The "{0}" Project Group has been created. This is '
                'a reminder to setup any permissions for the '
                'associated users.'.format(name),
                'from_email':
                settings.NO_REPLY_EMAIL,
                'recipient_list': [settings.SUPPORT_EMAIL],
            }
            # Since we aren't passing the fail_silently kwarg to the send_mail
            # method, it will throw any errors back in our face so we catch
            # them here and log them rather than letting it propogate.
            send_mail(**kwargs)
        except Exception:
            log.exception("Error sending project group notification email")

        log.info('Autocreate project group {0}'.format(group))
Esempio n. 38
0
    def test_group_assing(self):
        assign("change_contenttype", self.group, self.ctype)
        assign("delete_contenttype", self.group, self.ctype)

        check = ObjectPermissionChecker(self.group)
        self.assertTrue(check.has_perm("change_contenttype", self.ctype))
        self.assertTrue(check.has_perm("delete_contenttype", self.ctype))
Esempio n. 39
0
    def test_clean_perms(self):

        # assign obj perms
        target_perms = {
            self.target_user1: ["change_user"],
            self.target_group1: ["delete_group"],
            self.target_obj1: ["change_contenttype", "delete_contenttype"],
            self.target_obj2: ["change_contenttype"],
        }
        obj_perms_count = sum([len(val) for key, val in target_perms.items()])
        for target, perms in target_perms.items():
            target.__old_pk = target.pk # Store pkeys
            for perm in perms:
                assign(perm, self.user, target)

        # Remove targets
        for target, perms in target_perms.items():
            target.delete()

        # Clean orphans
        removed = clean_orphan_obj_perms()
        self.assertEqual(removed, obj_perms_count)

        # Recreate targets and check if user has no permissions
        for target, perms in target_perms.items():
            target.pk = target.__old_pk
            target.save()
            for perm in perms:
                self.assertFalse(self.user.has_perm(perm, target))
Esempio n. 40
0
    def test_published(self):
        concept = DataConcept(published=True)
        concept.save()
        DataConceptField(concept=concept, field=self.is_manager).save()
        DataConceptField(concept=concept, field=self.salary).save()

        # Published, not specific to any user
        self.assertEqual([x.pk for x in DataConcept.objects.published()], [])

        self.is_manager.published = True
        self.is_manager.save()
        self.salary.published = True
        self.salary.save()

        # Now published, it will appear
        self.assertEqual([x.pk for x in DataConcept.objects.published()], [1])

        user1 = User.objects.create_user('user1', 'user1')

        # Nothing since user1 cannot view either datafield
        self.assertEqual([x.pk for x in DataConcept.objects.published(user1)], [])

        assign('avocado.view_datafield', user1, self.is_manager)
        # Still nothing since user1 has no permission for salary
        self.assertEqual([x.pk for x in DataConcept.objects.published(user1)], [])

        assign('avocado.view_datafield', user1, self.salary)
        # Now user1 can see the concept
        self.assertEqual([x.pk for x in DataConcept.objects.published(user1)], [1])

        user2 = User.objects.create_user('user2', 'user2')

        # `user2` is not assigned
        self.assertEqual([x.pk for x in DataConcept.objects.published(user2)], [])
Esempio n. 41
0
    def test_clean_perms_command(self):
        """
        Same test as the one above but rather function directly, we call
        management command instead.
        """

        # assign obj perms
        target_perms = {
            self.target_user1: ["change_user"],
            self.target_group1: ["delete_group"],
            self.target_obj1: ["change_contenttype", "delete_contenttype"],
            self.target_obj2: ["change_contenttype"],
        }
        for target, perms in target_perms.items():
            target.__old_pk = target.pk # Store pkeys
            for perm in perms:
                assign(perm, self.user, target)

        # Remove targets
        for target, perms in target_perms.items():
            target.delete()

        # Clean orphans
        call_command("clean_orphan_obj_perms", verbosity=0)

        # Recreate targets and check if user has no permissions
        for target, perms in target_perms.items():
            target.pk = target.__old_pk
            target.save()
            for perm in perms:
                self.assertFalse(self.user.has_perm(perm, target))
Esempio n. 42
0
    def test_group_assing(self):
        assign("change_keycard", self.group, self.keycard)
        assign("delete_keycard", self.group, self.keycard)

        check = ObjectPermissionChecker(self.group)
        self.assertTrue(check.has_perm("change_keycard", self.keycard))
        self.assertTrue(check.has_perm("delete_keycard", self.keycard))
Esempio n. 43
0
def assign_permission(new_groups, objects, perm):
    groups = Group.objects.all()
    for obj in objects:
        for group in groups:
            remove_perm(perm, group, obj)
        for new_group in new_groups:
            assign(perm, new_group, obj)
Esempio n. 44
0
 def test_disallow_if_user_permission_revoked(self):
     self._create_user_and_login('alice')
     assign('change_xform', self.user, self.xform)
     response = self.client.get(self.url)
     remove_perm('change_xform', self.user, self.xform)
     response = self.client.get(self.url)
     self.assertEqual(response.status_code, 403)
Esempio n. 45
0
   def create_profile_and_userdetail(self, user):
      userDetail = UserDetail()
      userDetail.user = user
      userDetail.save()
      userena_profile = UserenaSignup.objects.create_userena_profile(user)

      # All users have an empty profile
      profile_model = get_profile_model()
      try:
         new_profile = user.get_profile()
      except profile_model.DoesNotExist:
         new_profile = profile_model(user=user)
         new_profile.save(using=self._db)

      # Give permissions to view and change profile
      for perm in ASSIGNED_PERMISSIONS['profile']:
         assign(perm[0], user, new_profile)

      # Give permissions to view and change itself
      for perm in ASSIGNED_PERMISSIONS['user']:
         assign(perm[0], user, user)

      if settings.USERENA_ACTIVATION_REQUIRED:
         userena_profile.send_activation_email()

      return user
Esempio n. 46
0
def add_change_profile_perm(sender, instance, created, raw, using, **kwargs):
    """ Adds 'change_profile' permission to created user objects """
    if created:
        try:
            assign('change_profile', instance, instance.get_profile())
        except:
            pass  # Anonymous user
Esempio n. 47
0
 def test_inactive_user_blocked(self):
     t = Thing(name='Test thing')
     t.save()
     self.user.is_active = False
     self.user.save()
     assign('change_thing', self.user, t)
     self.assertFalse(self.user.has_perm('tests.change_thing', t))
Esempio n. 48
0
    def test_decision_create_restricted(self):
        '''
        Decision create should be restricted to those with the organizations editor permission
        '''
        #first remove the permission
        remove_perm('edit_decisions_feedback', self.betty, self.bettysorg)

        #assert that creating a decision gives a 403
        path = reverse('publicweb_decision_create',
                       args=[self.bettysorg.slug, Decision.PROPOSAL_STATUS])
        response = self.client.get(path)
        self.assertEquals(response.status_code, 403)
        #give perm
        assign('edit_decisions_feedback', self.betty, self.bettysorg)
        # get a 200
        response = self.client.get(path)
        self.assertEquals(response.status_code, 200)

        # confirm 403 for different org
        bettys_unauthed_org = Organization.objects.get_for_user(self.betty)[1]
        path = reverse(
            'publicweb_decision_create',
            args=[bettys_unauthed_org.slug, Decision.PROPOSAL_STATUS])
        response = self.client.get(path)
        self.assertEquals(response.status_code, 403)
Esempio n. 49
0
    def test_object_permissions_win_over_group(self):
        t = Thing(name='Test thing')
        t.save()

        perm = Permission.objects.get(codename="add_thing")
        self.group.permissions.add(perm)
        perm = Permission.objects.get(codename="change_thing")
        self.group.permissions.add(perm)
        perm = Permission.objects.get(codename="delete_thing")
        self.group.permissions.add(perm)
        self.user.save()

        self.assertTrue(self.user.has_perm('tests.change_thing'))
        self.assertTrue(self.user.has_perm('tests.add_thing'))
        self.assertTrue(self.user.has_perm('tests.delete_thing'))

        self.assertTrue(self.user.has_perm('tests.change_thing', t))
        self.assertTrue(self.user.has_perm('tests.add_thing', t))
        self.assertTrue(self.user.has_perm('tests.delete_thing', t))

        assign('change_thing', self.group, t)  # per-object permission

        self.assertTrue(self.user.has_perm('tests.change_thing', t))
        self.assertFalse(self.user.has_perm('tests.add_thing', t))
        self.assertFalse(self.user.has_perm('tests.delete_thing', t))
Esempio n. 50
0
    def test_scorecard_pdf(self):

        # add standard to the season
        self.setUpStandardsForSeason(self.rwanda_2010)

        # create a scorecard
        scorecard = Scorecard.objects.create(season=self.rwanda_2010, wetmill=self.nasho,
                                             created_by=self.admin, modified_by=self.admin)

        # try to get a pdf report, remember this user haven't any permission
        self.login(self.viewer)
        response = self.client.get(reverse('scorecards.scorecard_pdf', args=[scorecard.id]))
        # should be redirected, you don't have permission fella..
        self.assertEquals(302, response.status_code)
        self.client.logout()

        # lets upgrade this user to be a viewer
        assign('wetmills.wetmill_report_view', self.viewer)
        self.login(self.viewer)
        response = self.client.get(reverse('scorecards.scorecard_pdf', args=[scorecard.id]))
        # it works!
        self.assertEquals(200, response.status_code)
        self.client.logout()

        # try again with a strong dude! Admin...
        self.login(self.admin)
        response = self.client.get(reverse('scorecards.scorecard_pdf', args=[scorecard.id]))
        # everybody! open the doors and pay respect to the admin
        self.assertEquals(200, response.status_code)
 def test_group_remove_perm_global(self):
     # assign perm first
     perm = "contenttypes.change_contenttype"
     assign(perm, self.group)
     remove_perm(perm, self.group)
     group_perms = GroupPermissionList.objects.get(group=self.group).permission_list
     self.assertFalse(perm in group_perms)
Esempio n. 52
0
    def test_get_sorted_nodeset_list(self):
        '''Get a list of NodeSets with sorting params applied (e.g., order_by=name)

        '''
        nodeset1 = NodeSet.objects.create(name='ns1',
                                          study=self.study,
                                          assay=self.assay,
                                          node_count=1,
                                          is_implicit=True,
                                          solr_query=simplejson.dumps(
                                              self.query))
        assign("read_%s" % nodeset1._meta.module_name, self.user, nodeset1)
        nodeset2 = NodeSet.objects.create(name='ns2',
                                          study=self.study2,
                                          assay=self.assay2,
                                          node_count=1,
                                          is_implicit=True,
                                          solr_query=simplejson.dumps(
                                              self.query))
        assign("read_%s" % nodeset2._meta.module_name, self.user, nodeset2)

        response = self.api_client.get(self.nodeset_uri,
                                       format='json',
                                       authentication=self.get_credentials(),
                                       data={'order_by': 'name'})
        self.assertValidJSONResponse(response)
        data = self.deserialize(response)['objects']
        self.assertEqual(len(data), 2)
        self.assertEqual(data[0]['name'], nodeset1.name)
Esempio n. 53
0
    def save(self, *args, **kwargs):
        if not self.slug:
            # Subdomains can't have underscores in them.
            self.slug = slugify(self.name).replace('_', '-')
            if self.slug == '':
                raise Exception(_("Model must have slug"))
        super(Project, self).save(*args, **kwargs)
        for owner in self.users.all():
            assign('view_project', owner, self)

        # Add exceptions here for safety
        try:
            self.sync_supported_versions()
        except Exception:
            log.error('failed to sync supported versions', exc_info=True)
        try:
            symlink(project=self.slug)
        except Exception:
            log.error('failed to symlink project', exc_info=True)
        try:
            update_static_metadata(project_pk=self.pk)
        except Exception:
            log.error('failed to update static metadata', exc_info=True)
        try:
            branch = self.default_branch or self.vcs_repo().fallback_branch
            if not self.versions.filter(slug='latest').exists():
                self.versions.create(slug='latest', verbose_name='latest', machine=True, type='branch', active=True, identifier=branch)
            # if not self.versions.filter(slug='stable').exists():
            #     self.versions.create(slug='stable', verbose_name='stable', type='branch', active=True, identifier=branch)
        except Exception:
            log.error('Error creating default branches', exc_info=True)
Esempio n. 54
0
    def test_get_analysis_list_for_given_dataset(self):
        '''Test retrieving a list of Analysis instances for a given dataset.

        '''
        analysis1 = Analysis.objects.create(name='a1',
                                            project=self.project,
                                            data_set=self.dataset,
                                            workflow=self.workflow)
        assign("read_%s" % Analysis._meta.module_name, self.user, analysis1)
        analysis2 = Analysis.objects.create(name='a2',
                                            project=self.project,
                                            data_set=self.dataset2,
                                            workflow=self.workflow)
        assign("read_%s" % Analysis._meta.module_name, self.user, analysis2)
        analysis_uri = make_api_uri(Analysis._meta.module_name)
        response = self.api_client.get(
            analysis_uri,
            format='json',
            data={'data_set__uuid': self.dataset.uuid},
            authentication=self.get_credentials())
        self.assertValidJSONResponse(response)
        data = self.deserialize(response)['objects']
        self.assertEqual(len(data), 1)
        self.assertKeys(data[0],
                        ['uuid', 'name', 'creation_date', 'resource_uri'])
        self.assertEqual(data[0]['name'], analysis1.name)
Esempio n. 55
0
    def test_user_has_access_on_model_with_metaclass(self):
        """
        Test to the fix issues of comparaison made via type()
        in the decorator. In the case of a `Model` implementing
        a custom metaclass, the decorator fail because type
        doesn't return `ModelBase`
        """
        perm = "auth.change_user"

        class TestMeta(ModelBase):
            pass

        class ProxyUser(User):
            class Meta:
                proxy = True
                app_label = "auth"

            __metaclass__ = TestMeta

        joe, created = ProxyUser.objects.get_or_create(username="******")
        assign(perm, self.user, obj=joe)

        request = self._get_request(self.user)

        @permission_required_or_403(perm, (ProxyUser, "username", "username"))
        def dummy_view(request, username):
            return HttpResponse("dummy_view")

        response = dummy_view(request, username="******")
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, "dummy_view")
Esempio n. 56
0
 def save(self, *args, **kw):
     #TODO: abort save if sent
     if self.pk is not None:
         orig = Request.objects.get(pk=self.pk)
         if orig.private != self.private:
             logger.info("request %s privacy changed to=%s from=%s" % (self.slug, self.private, orig.private))
             group, g_created = Group.objects.get_or_create(name='public')
             if self.private == True:
                 remove_perm(Request.get_permission_name('view'), group, self)
                 logger.info('request %s permissions changed: removed from public' % (self.slug))
             else:
                 assign(Request.get_permission_name('view'), group, self)
                 logger.info('request %s permissions changed: added to public' % (self.slug))
         #import pdb;pdb.set_trace()
         if self.contacts is not None and self.contacts.count() > 0 and self.contacts.all()[0].get_related_agencies().count() > 0:
             self.agency = self.contacts.all()[0].get_related_agencies()[0]
             self.government = self.agency.government
         else:
             self.agency = None
             self.government = None
     else:
         self.status = 'I'
         code = "LOOKUP:" + User.objects.make_random_password(length=64)
         while Request.objects.filter(thread_lookup=code):
             code = User.objects.make_random_password(length=64)
         self.thread_lookup = code
     super(Request, self).save(*args, **kw)
 def test_remove_perm(self):
     assign('guardian.change_keyvalue', self.user, self.keyval)
     self.assertTrue(self.user.has_perm('guardian.change_keyvalue',
         self.keyval))
     remove_perm('guardian.change_keyvalue', self.user, self.keyval)
     self.assertFalse(self.user.has_perm('guardian.change_keyvalue',
         self.keyval))
Esempio n. 58
0
    def test_group_assing(self):
        assign("change_flatpage", self.group, self.flatpage)
        assign("delete_flatpage", self.group, self.flatpage)

        check = ObjectPermissionChecker(self.group)
        self.assertTrue(check.has_perm("change_flatpage", self.flatpage))
        self.assertTrue(check.has_perm("delete_flatpage", self.flatpage))
Esempio n. 59
0
def add_collaborator_(request, pk):
    data = {'valid': False}
    tl = Timeline.objects.get(pk=pk)
    if tl.created_by != request.user:
        return render_json_response(data)
    if request.method == "POST":
        username = request.POST.get('username', '')
        try:
            user = User.objects.get(username=username)
            if user.has_perm('collaborator', tl):
                data['info'] = u'用户 "%s" 已经添加过' % username
                return render_json_response(data)
        except:
            data['info'] = u'用户 "%s" 不存在' % username
            return render_json_response(data)
        assign('collaborator', user, tl)
        return render_json_response({
            'valid':
            True,
            'obj': {
                'pk': user.pk,
                'username': user.username
            },
            'html':
            render_string(COLLABORATOR_ROW_TMPL, {'o': user})
        })
    return render_json_response(data)