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)
Beispiel #2
0
    def form_valid(self, form):
        """
        Comprobar validez del formulario.

        :param form:formulario recibido.
        :return:URL de redireccion correcta.
        """
        super(RolUpdate, self).form_valid(form)

        # eliminamos permisos anteriores.
        self.object.permissions.clear()
        choosed_perms = get_selected_perms(self.request.POST)
        for permname in choosed_perms:
            perm = Permission.objects.get(codename=permname)
            self.object.permissions.add(perm)

        # actualizamos los permisos de los miembros de equipos que tienen este rol.
        team_members_set = self.object.miembroequipo_set.all()
        for team_member in team_members_set:
            user = team_member.usuario
            project = team_member.proyecto
            # borramos todos los permisos que tiene asociado el usuario en el proyecto.
            for perm in get_perms(user, project):
                # no eliminar el permiso view_project.
                if perm != 'view_project':
                    remove_perm(perm, user, project)

            all_roles = team_member.roles.all()
            for role in all_roles:
                # desacociamos al usuario de los demas roles con los que contaba (para que se eliminen los permisos anteriores).
                team_member.roles.remove(role)
                # volvemos a agregar para que se copien los permisos actualizados.
                team_member.roles.add(role)
        return HttpResponseRedirect(self.get_success_url())
Beispiel #3
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_group_remove_perm(self):
        # assign perm first
        assign_perm("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))
    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))
 def test_remove_perm(self):
     assign_perm('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))
Beispiel #7
0
    def test_unpublished_layer(self):
        """With resource publishing"""
        layer = Layer.objects.filter(alternate='geonode:CA')[0]
        layer.is_published = False
        layer.save()

        user = get_user_model().objects.get(username='******')
        self.client.login(username='******', password='******')
        # 404 if layer is unpublished
        response = self.client.get(reverse('layer_detail', args=('geonode:CA',)))
        self.failUnlessEqual(response.status_code, 404)

        # 404 if layer is unpublished but user has permission but does not belong to the group
        assign_perm('publish_resourcebase', user, layer.get_self_resource())
        response = self.client.get(reverse('layer_detail', args=('geonode:CA',)))
        self.failUnlessEqual(response.status_code, 404)

        # 200 if layer is unpublished and user is owner
        remove_perm('publish_resourcebase', user, layer.get_self_resource())
        layer.owner = user
        layer.save()
        response = self.client.get(reverse('layer_detail', args=('geonode:CA',)))
        self.failUnlessEqual(response.status_code, 200)

        # 200 if layer is published
        layer.is_published = True
        layer.save()

        response = self.client.get(reverse('layer_detail', args=('geonode:CA',)))
        self.failUnlessEqual(response.status_code, 200)

        layer.is_published = True
        layer.save()
Beispiel #8
0
    def form_valid(self, form):
        '''
       # actualiza los miembros del equipo del proyecto que se hayan especifico

        #:param form: formulario de edición del proyecto
        '''
        self.object = form.save()
        formset = self.TeamMemberInlineFormSet(self.request.POST, instance=self.object)
        if formset.is_valid():
            # borramos todos los permisos asociados al usuario en el proyecto antes de volver a asignar los nuevos
            proyecto = self.object
            for form in formset:
                if form.has_changed():  #solo los formularios con cambios efectuados
                    user = form.cleaned_data['usuario']
                    if('usuario' in form.changed_data and 'usuario' in form.initial): #si se cambia el usuario, borrar permisos del usuario anterior
                        original_user = get_object_or_404(User, pk=form.initial['usuario'])
                        for perm in get_perms(original_user, proyecto):
                            remove_perm(perm, original_user, proyecto)
                    else:
                        for perm in get_perms(user, proyecto):
                            remove_perm(perm, user, proyecto)

            formset.save()
            return HttpResponseRedirect(reverse('project_list'))

        return render(self.request, self.get_template_names(), {'form': form, 'formset': formset},
                      context_instance=RequestContext(self.request))
Beispiel #9
0
 def perform_destroy(self, instance):
     model_cls = self.get_model_cls()
     app_label = model_cls._meta.app_label
     model_name = model_cls._meta.model_name
     for perm in instance['permissions']:
         remove_perm('%s.%s_%s' % (app_label, perm, model_name),
                     instance[self.get_user_or_group()])
Beispiel #10
0
    def test_map_download(self):
        """Test the correct permissions on layers on map download"""
        create_models(type='map')
        create_maplayers()
        # Get a Map
        the_map = Map.objects.get(title='GeoNode Default Map')

        # Get a MapLayer and set the parameters as it is local and not a background
        # and leave it alone in the map
        map_layer = the_map.layer_set.get(name='geonode:CA')
        map_layer.local = True
        map_layer.group = 'overlay'
        map_layer.save()
        the_map.layer_set.all().delete()
        the_map.layer_set.add(map_layer)

        # Get the Layer and set the permissions for bobby to it and the map
        bobby = Profile.objects.get(username='******')
        the_layer = Layer.objects.get(typename='geonode:CA')
        remove_perm('download_resourcebase', bobby, the_layer.get_self_resource())
        remove_perm('download_resourcebase', Group.objects.get(name='anonymous'),
                    the_layer.get_self_resource())
        assign_perm('view_resourcebase', bobby, the_layer.get_self_resource())
        assign_perm('download_resourcebase', bobby, the_map.get_self_resource())

        self.client.login(username='******', password='******')

        response = self.client.get(reverse('map_download', args=(the_map.id,)))
        self.assertTrue('Could not find downloadable layers for this map' in response.content)
Beispiel #11
0
    def test_view_permissions_for_logged_in_user(self):
        # check that user is not allowed to see information document
        document = Document.objects.get()

        response = self.app.get(
            reverse("information_pages:view_information", args=[document.url_title]), user=self.user, status=403
        )
        self.assertEqual(response.status_code, 403)

        # grant view permission to that user
        assign_perm(InformationDocument.VIEW_PERMISSION_NAME, self.user, document)
        response = self.app.get(
            reverse("information_pages:view_information", args=[document.url_title]), user=self.user
        )
        self.assertEqual(response.status_code, 200)
        remove_perm(InformationDocument.VIEW_PERMISSION_NAME, self.user, document)

        # check that user is not allowed to see page anymore
        response = self.app.get(
            reverse("information_pages:view_information", args=[document.url_title]), user=self.user, status=403
        )
        self.assertEqual(response.status_code, 403)

        # add user to test group and test that he is now allowed to see that document
        self.user.groups.add(self.group)
        self.user.save()

        response = self.app.get(
            reverse("information_pages:view_information", args=[document.url_title]), user=self.user
        )
        self.assertEqual(response.status_code, 200)
Beispiel #12
0
def view_solutions(request, quiz_id):
    if request.method == 'GET':
        quiz = get_object_or_404(Quiz, pk=quiz_id)
        u = request.user
        p = u.profile

        # Make sure student has already answered the quiz
        try:
            answer_sheet = AnswerSheet.objects.get(quiz=quiz, owner=p)
        except AnswerSheet.DoesNotExist:
            answer_sheet = None

        if answer_sheet is None or not answer_sheet.submitted:
            return HttpResponseForbidden()

        # After student views the answer, he cannot change his answers
        answer_sheet.confirmed = True
        answer_sheet.save()

        # Remove student's permission to change answers
        perm = 'attempt_quiz'
        if request.user.has_perm(perm, quiz):
            remove_perm(perm, u, quiz)

        questions = Question.objects.filter(quiz=quiz)
        student_answers = answer_sheet.answers.all()

        # Build a map between question_id and answer
        answers = {a.question_id: a.answer for a in student_answers}

        for question in questions:
            question.answer = answers[question.id]

        context = {'questions': questions}
        return render(request, 'quizzes/view_solutions.html', context)
def shares_edit(message):
    data = json.loads(message['data'])
    workspace = get_object_or_404(Project, pk=data['workspace_id'])
    user = get_object_or_404(User, username=data['username'])
    perms = data.get('permissions', '').split(',')
    
    if not message.user.has_perm('falkor.can_edit_shares', workspace):
        return
    
    if user == workspace.user:
        Group("user-%s" % message.user.pk).send(create_event('notifications', {'level': 'info', 'message': 'you cannot change permissions of the owner'}))
        return
    
    permissions = ['can_open_ide']
    print 'ERR', user, perms
    for perm in permissions:
        if perm in perms:
            print 'Adding', perm, 'for', user
            assign_perm(perm, user, workspace)
        else:
            print 'Removing', perm, 'for', user
            remove_perm(perm, user, workspace)
    
    cli = docker_cli()
    get_workspace_full(cli, message.user, workspace)
    
    Group("user-%s" % message.user.pk).send(create_event('workspaces.select', model_to_dict(workspace)))
Beispiel #14
0
    def test_create_permissions_for_anonymous_user(self):
        anonymous_user = get_anonymous_user()

        # check that anonymous user is not allowed to see that document
        response = self.app.get(reverse("information_pages:create"), user=anonymous_user, status=403)
        self.assertEqual(response.status_code, 403)

        # allow anonymous users to see that document and test that
        assign_perm("information_pages.add_informationdocument", anonymous_user)
        assign_perm("information_pages.change_informationdocument", anonymous_user)

        # it should work now
        response = self.app.get(reverse("information_pages:create"), user=anonymous_user)
        self.assertEqual(response.status_code, 200)

        remove_perm("information_pages.add_informationdocument", anonymous_user)
        remove_perm("information_pages.change_informationdocument", anonymous_user)

        # check that anonymous user is not allowed to see page anymore
        response = self.app.get(reverse("information_pages:create"), user=anonymous_user, status=403)
        self.assertEqual(response.status_code, 403)

        # test the same with group
        anonymous_user.groups.add(self.group)
        anonymous_user.save()

        response = self.app.get(reverse("information_pages:create"))
        self.assertEqual(response.status_code, 200)
Beispiel #15
0
    def post(self, request, format=None, **kwargs):
        host = get_object_or_404(Host, pk=kwargs['pk'])
        serializer = host_serializers.HostOwnerSerializer(data=request.data)
        if serializer.is_valid():
            user_list = serializer.data.get('users')
            group_list = serializer.data.get('groups')

            if user_list:
                users = User.objects.none()
                for username in user_list:
                    users |= User.objects.filter(username__iexact=username)

                for user in users:
                    remove_perm('hosts.is_owner_host', user, host)

            if group_list:
                groups = Group.objects.none()
                for groupname in group_list:
                    groups |= Group.objects.filter(name__iexact=groupname)

                for group in groups:
                    remove_perm('hosts.is_owner_host', group, host)

            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Beispiel #16
0
    def test_permissions(self):
        """
        Generic method to test permissions for each resource
        """
        if not self._error_check_permissions():
            # Just succeed immediately if necessary
            return

        self.client.login(username='******', password='******')

        endpoint = self.permission_tests['endpoint'].format(self.obj.pk)

        # Iterate over the methods / permissions
        for perm_type in self.permission_tests['permission_types']:
            # Should fail now - no permission

            method = perm_type['method']

            response = getattr(self.client, method)(endpoint, perm_type.get('data', {}))
            self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

            # Assign permission
            assign_perm(self.permission_tests['permission'] % perm_type['perm'],
                        self.user, self.obj)

            # Should work now - permission granted
            response = getattr(self.client, method)(endpoint, perm_type.get('data', {}))
            expected_code = perm_type.get('code', status.HTTP_200_OK)

            self.assertEqual(response.status_code, expected_code)

            # Remove permission
            remove_perm(self.permission_tests['permission'] % perm_type['perm'],
                        self.user, self.obj)
Beispiel #17
0
    def test_unpublished_layer(self):
        """Test unpublished layer behaviour"""

        user = get_user_model().objects.get(username='******')
        self.client.login(username='******', password='******')

        # default (RESOURCE_PUBLISHING=False)
        # access to layer detail page gives 200 if layer is published or
        # unpublished
        response = self.client.get(reverse('layer_detail', args=('geonode:CA',)))
        self.failUnlessEqual(response.status_code, 200)
        layer = Layer.objects.filter(title='CA')[0]
        layer.is_published = False
        layer.save()
        response = self.client.get(reverse('layer_detail', args=('geonode:CA',)))
        self.failUnlessEqual(response.status_code, 200)

        # with resource publishing
        with self.settings(RESOURCE_PUBLISHING=True):
            # 404 if layer is unpublished
            response = self.client.get(reverse('layer_detail', args=('geonode:CA',)))
            self.failUnlessEqual(response.status_code, 404)
            # 200 if layer is unpublished but user has permission
            assign_perm('publish_resourcebase', user, layer.get_self_resource())
            response = self.client.get(reverse('layer_detail', args=('geonode:CA',)))
            self.failUnlessEqual(response.status_code, 200)
            # 200 if layer is published
            layer.is_published = True
            layer.save()
            remove_perm('publish_resourcebase', user, layer.get_self_resource())
            response = self.client.get(reverse('layer_detail', args=('geonode:CA',)))
            self.failUnlessEqual(response.status_code, 200)

        layer.is_published = True
        layer.save()
    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))
Beispiel #19
0
    def test_users_with_model_perms_attach_perms(self):
        for perm in CloudAccount.model_permissions:
            users = shortcuts.get_users_with_model_perms(
                CloudAccount,
                attach_perms=True,
                with_group_users=False,
                with_superusers=False,
            )

            self.assertIsInstance(users, dict)
            self.assertEqual(len(users), 0)

            assign_perm('cloud.%s_cloudaccount' % perm, self.user)

            users = shortcuts.get_users_with_model_perms(
                CloudAccount,
                attach_perms=True,
                with_group_users=False,
                with_superusers=False,
            )

            self.assertIsInstance(users, dict)
            self.assertEqual(len(users), 1)
            self.assertTrue(self.user in users)
            self.assertEqual(users[self.user], ['%s_cloudaccount' % perm])

            remove_perm('cloud.%s_cloudaccount' % perm, self.user)
Beispiel #20
0
 def set_free_resources(self, user):
     ''
     manager = self.get_managers()[0]
     for resource in self.resources_by_user(user):
         remove_perm('view_resourcebase', manager, resource)
     
     AppMember.objects.get(app=self, user=user).delete()
Beispiel #21
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))
 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)
Beispiel #23
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)
Beispiel #24
0
 def form_valid(self, form):
     old_course = models.Course.objects.get(pk=form.instance.pk)
     initial_instructors = list(old_course.instructors.all())
     initial_students = list(old_course.students.all())
     
     response = super(CourseUpdate, self).form_valid(form)
     
     instructors = form.instance.instructors.all()
     students = form.instance.students.all()
     
     # print(initial_instructors)
     # print(instructors)
     # print(initial_students)
     # print(students)
     
     # Revoke permissions
     for user in initial_instructors:
         remove_perm('change_course', user, form.instance)
         remove_perm('view_course', user, form.instance)
         remove_perm('instruct_course', user, form.instance)
     for user in initial_students:
         remove_perm('view_course', user, form.instance)
         remove_perm('enroll_course', user, form.instance)
     
     # Assign permissions
     for user in instructors:
         assign_perm('change_course', user, form.instance)
         assign_perm('view_course', user, form.instance)
         assign_perm('instruct_course', user, form.instance)
     for user in students:
         assign_perm('view_course', user, form.instance)
         assign_perm('enroll_course', user, form.instance)
     
     return response
Beispiel #25
0
    def save_model(self, request, obj, form, change):
        new_flag = obj._state.adding
        if request.user.is_authenticated:
            obj.updated_by = request.user
            if new_flag:
                obj.created_by = request.user

        super().save_model(request, obj, form, change)
        if new_flag:
            logger.info("User(%i) creating Project(%i) %s", request.user.id, obj.id, obj.name)
        else:
            logger.info("User(%i) updating Project(%i) %s", request.user.id, obj.id, obj.name)

        if 'custom_permissions' in form.data:
            if 'worker_permissions' in form.data:
                existing_groups = set(get_groups_with_perms(obj))
                form_groups = set(form.cleaned_data['worker_permissions'])
                groups_to_add = form_groups.difference(existing_groups)
                groups_to_remove = existing_groups.difference(form_groups)
                for group in groups_to_add:
                    assign_perm('can_work_on', group, obj)
                for group in groups_to_remove:
                    remove_perm('can_work_on', group, obj)
            else:
                for group in get_groups_with_perms(obj):
                    remove_perm('can_work_on', group, obj)
Beispiel #26
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
Beispiel #27
0
def add_user_to_sheet(request, slug):
    sheet = get_object_or_404(Sheet, slug=slug)
    form_by_username = AddUserForm(request.POST or None)
    groups = UserAPI.get_groups_and_users_dict().keys()

    by_username_valid = form_by_username.is_valid()

    if by_username_valid:
        users = list()
        username = form_by_username.cleaned_data['username']
        if username:
            users.append(get_object_or_404(User, username=username))
        for group in groups:
            selected_users_pk = form_by_username.cleaned_data[group]
            for pk in selected_users_pk:
                users.append(get_object_or_404(User, pk=pk))

        for user in users:
            if user != request.user:
                remove_perm('sheets.change_sheet', user, sheet)
            assign_perm('sheets.view_sheet', user, sheet)
            if form_by_username.cleaned_data['role'] == 'T':
                assign_perm('sheets.change_sheet', user, sheet)
            else:
                MarkAPI.create_marks_for_student(sheet, user)

        return redirect('sheet_detail', slug=slug)

    return render(request, 'add_user_to_sheet.html', {
        'form_by_username': form_by_username,
        'sheet': sheet
    })
Beispiel #28
0
    def update(self, request, pk):
        """
        Add or remove permissions
        """
        if not request.user.is_authenticated():
            return Response(
                    status=403,
                    data={
                        'detail': 'Authentication required',
                        },
                    )
        required_params = ['user', ]
        for param in required_params:
            if param not in request.DATA:
                return Response(
                        status=400,
                        data={
                            'detail': 'Parameter required {param}'.format(
                                param=param,
                                ),
                            },
                        )
        check_list = get_object_or_404(CheckList, id=pk)
        if not request.user.has_perm('api.change_checklist', check_list):
            return Response(
                    status=403,
                    data={
                        'detail': 'Permission denied',
                        },
                    )
        user = get_object_or_404(User, id=request.DATA.get('user'), )
        if user.id == check_list.owner.id:
            return Response(
                    status=400,
                    data={
                        'detail': "Owner permissions can't be changed",
                        },
                    )

        if user.has_perm('api.change_checklist', check_list):
            remove_perm('api.view_checklist', user, check_list)
            remove_perm('api.change_checklist', user, check_list)
        else:
            assign_perm('api.view_checklist', user, check_list)
            assign_perm('api.change_checklist', user, check_list)

        return Response(
                status=200,
                data={
                    'change_checklist': user.has_perm(
                        'api.change_checklist',
                        check_list
                        ),
                    'detail': 'Permissions updated',
                    'view_checklist': user.has_perm(
                        'api.view_checklist',
                        check_list
                        ),
                    },
                )
 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))
Beispiel #30
0
    def test_view_permissions_for_anonymous_user(self):
        anonymous_user = get_anonymous_user()
        document = Document.objects.get()

        # check that anonymous user is not allowed to see that document
        response = self.app.get(
            reverse("information_pages:view_information", args=[document.url_title]), user=anonymous_user, status=403
        )
        self.assertEqual(response.status_code, 403)

        # allow anonymous users to see that document and test that
        assign_perm(InformationDocument.VIEW_PERMISSION_NAME, anonymous_user, document)

        # it should work now
        response = self.app.get(
            reverse("information_pages:view_information", args=[document.url_title]), user=anonymous_user
        )
        self.assertEqual(response.status_code, 200)

        remove_perm(InformationDocument.VIEW_PERMISSION_NAME, anonymous_user, document)

        # check that anonymous user is not allowed to see page anymore
        response = self.app.get(
            reverse("information_pages:view_information", args=[document.url_title]), user=anonymous_user, status=403
        )
        self.assertEqual(response.status_code, 403)

        # test the same with group
        anonymous_user.groups.add(self.group)
        anonymous_user.save()

        response = self.app.get(
            reverse("information_pages:view_information", args=[document.url_title]), user=anonymous_user
        )
        self.assertEqual(response.status_code, 200)
Beispiel #31
0
 def set_privacy(self, privacy_level):
     # TODO: Check for results of the assign_perm and remove_perm calls
     anon = get_anonymous_user()
     retval = True
     if privacy_level == Grow.PRIVACY_PUBLISHED:
         self.published = True
         assign_perm('view_grow', anon, self)
     elif privacy_level == Grow.PRIVACY_HIDDEN:
         self.published = False
         print self.published
         assign_perm('view_grow', anon, self)
     elif privacy_level == Grow.PRIVACY_PRIVATE:
         self.published = False
         remove_perm('view_grow', anon, self)
     else:
         retval = False
     self.save()
     return retval
Beispiel #32
0
def delete_project_locus_lists(request, project_guid):
    project = get_project_and_check_permissions(project_guid, request.user,
                                                CAN_EDIT)
    request_json = json.loads(request.body)
    locus_lists = LocusList.objects.filter(
        guid__in=request_json['locusListGuids'])
    for locus_list in locus_lists:
        remove_perm(user_or_group=project.can_view_group,
                    perm=CAN_VIEW,
                    obj=locus_list)

    return create_json_response({
        'locusListGuids': [
            locus_list['locusListGuid']
            for locus_list in get_sorted_project_locus_lists(
                project, request.user)
        ],
    })
Beispiel #33
0
    def save(self, commit=True):
        """
        Saves granted permissions and removes those switched off.
        """
        group, project = self.team.group, self.team.project

        granted_perms = self.cleaned_data['permissions']
        team_perms = get_perms(group, project)
        # Grant permissions
        for perm in granted_perms:
            if perm not in team_perms:
                assign(perm, group, project)
                self._message('info', _("Permission added: %s" % perm))
        # Remove permissions
        for perm in team_perms:
            if perm not in granted_perms:
                remove_perm(perm, group, project)
                self._message('warning', _("Permission removed: %s" % perm))
def change_permission_owner(self):
    owner_permissions = [
        'view_expressionstudy', 'change_expressionstudy',
        'delete_expressionstudy'
    ]

    if self.initial_owner:
        # If update, remove permission, else do nothing
        if self.initial_owner != self.created_by:
            initial_owner_permission = get_user_perms(self.initial_owner, self)
            for permission in owner_permissions:
                if permission in initial_owner_permission:
                    remove_perm(permission, self.initial_owner, self)

    user_permissions = get_user_perms(self.created_by, self)
    for permission in owner_permissions:
        if permission not in user_permissions:
            assign_perm(permission, self.created_by, self)
Beispiel #35
0
    def test_can_see_link_details(self):
        extra_sub_item = baker.make(MenuItem,
                                    parent=self.root_menu_item,
                                    title_en="name",
                                    link="link123")

        assign_perm(MenuItem.EDIT_PERMISSION_NAME, self.user, extra_sub_item)

        response = self.app.get(reverse('menu_items_index'), user=self.user)
        self.assertEqual(response.status_code, 200)
        self.assertIn("(<i>Link:</i> link123)", response.body.decode('utf-8'))

        remove_perm(MenuItem.EDIT_PERMISSION_NAME, self.user, extra_sub_item)

        response = self.app.get(reverse('menu_items_index'), user=self.user)
        self.assertEqual(response.status_code, 200)
        self.assertNotIn("(<i>Link:</i> link123)",
                         response.body.decode('utf-8'))
Beispiel #36
0
    def update_viewer_groups_permissions(self, *, exclude_jobs=None):
        """
        Update the permissions for the algorithm jobs viewers groups to
        view this image.

        Parameters
        ----------
        exclude_jobs
            Exclude these results from being considered. This is useful
            when a many to many relationship is being cleared to remove this
            image from the results image set, and is used when the pre_clear
            signal is sent.
        """
        if exclude_jobs is None:
            exclude_jobs = []

        algorithm_jobs_groups = (Q(job__inputs__image=self) | Q(
            job__outputs__image=self)) & ~Q(job__in=exclude_jobs)
        reader_studies_groups = Q(
            editors_of_readerstudy__images__id__exact=self.pk) | Q(
                readers_of_readerstudy__images__id__exact=self.pk)
        archive_groups = (Q(editors_of_archive__images__id__exact=self.pk)
                          | Q(uploaders_of_archive__images__id__exact=self.pk)
                          | Q(users_of_archive__images__id__exact=self.pk))

        expected_groups = {
            *Group.objects.filter(algorithm_jobs_groups | reader_studies_groups
                                  | archive_groups).distinct()
        }

        current_groups = get_groups_with_perms(self, attach_perms=True)
        current_groups = {
            group
            for group, perms in current_groups.items() if "view_image" in perms
        }

        groups_missing_perms = expected_groups - current_groups
        groups_with_extra_perms = current_groups - expected_groups

        for g in groups_missing_perms:
            assign_perm("view_image", g, self)

        for g in groups_with_extra_perms:
            remove_perm("view_image", g, self)
Beispiel #37
0
    def test_v1_user_not_authorized_run_playbook_tags(
            self, mock_task_run_playbook_delay):
        """
        Ensure an unauthorized user can't override tags.
        """
        mock_task_run_playbook_delay.return_value = celery.result.AsyncResult(
            id='fake-id')
        url = '/api/v1/playbooks/%s/run/' % self.playbook.name
        self.client.credentials(HTTP_AUTHORIZATION='Token ' +
                                self.user_authorized_token.key)

        # Testing only tags permission
        remove_perm('playbook.can_override_only_tags', self.user_authorized,
                    self.playbook)
        data = {
            'only_tags': u'deploy,test',
        }
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        assign_perm('playbook.can_override_only_tags', self.user_authorized,
                    self.playbook)

        # Testing skip tags permission
        remove_perm('playbook.can_override_skip_tags', self.user_authorized,
                    self.playbook)
        data = {
            'skip_tags': u'base,test',
        }
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        assign_perm('playbook.can_override_skip_tags', self.user_authorized,
                    self.playbook)

        # Testing extra_vars permission
        remove_perm('playbook.can_override_extra_vars', self.user_authorized,
                    self.playbook)
        data = {
            'extra_vars': u'env=test',
        }
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        assign_perm('playbook.can_override_extra_vars', self.user_authorized,
                    self.playbook)

        # Testing subset permission
        remove_perm('playbook.can_override_subset', self.user_authorized,
                    self.playbook)
        data = {
            'subset': u'localhost',
        }
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
        assign_perm('playbook.can_override_subset', self.user_authorized,
                    self.playbook)
Beispiel #38
0
    def delete(self, request, group_name, user_name):
        """
        Removes a maintainer form the group
        Args:
            request: Django rest framework request
            group_name:Group name from the request
            user_name: User name from the request

        Returns:
            Http status of the request

        """
        try:
            if user_name is None:
                return BossHTTPError('Missing username parameter in post.',
                                     ErrorCodes.INVALID_URL)

            group = Group.objects.get(name=group_name)
            bgroup = BossGroup.objects.get(group=group)

            # Check the users permissions.
            if request.user.has_perm("maintain_group", bgroup):
                usr = User.objects.get(username=user_name)
                status = usr.has_perm('maintain_group', bgroup)

                if status is False:
                    return BossHTTPError(
                        'The user {} does not have the {} permission on the group {}'
                        .format(usr.username, 'maintain_group',
                                group_name), ErrorCodes.MISSING_PERMISSION)
                else:
                    remove_perm('maintain_group', usr, bgroup)

                return HttpResponse(status=204)
            else:
                return BossHTTPError(
                    'The user {} does not have the {} permission on the group {}'
                    .format(request.user.username, 'maintain_group',
                            group_name), ErrorCodes.MISSING_PERMISSION)

        except Group.DoesNotExist:
            return BossGroupNotFoundError(group_name)
        except User.DoesNotExist:
            return BossUserNotFoundError(user_name)
Beispiel #39
0
    def test_permission_required_views(self, client):
        rius = RawImageUploadSessionFactory()
        image_file = ImageFileFactory(image_type="DZI")
        u = UserFactory()

        for view_name, kwargs, permission, obj in [
            (
                "raw-image-upload-session-detail",
                {
                    "pk": rius.pk
                },
                "view_rawimageuploadsession",
                rius,
            ),
            (
                "osd-image-detail",
                {
                    "pk": image_file.image.pk
                },
                "view_image",
                image_file.image,
            ),
        ]:
            response = get_view_for_user(
                client=client,
                viewname=f"cases:{view_name}",
                reverse_kwargs=kwargs,
                user=u,
            )

            assert response.status_code == 403

            assign_perm(permission, u, obj)

            response = get_view_for_user(
                client=client,
                viewname=f"cases:{view_name}",
                reverse_kwargs=kwargs,
                user=u,
            )

            assert response.status_code == 200

            remove_perm(permission, u, obj)
Beispiel #40
0
def set_perms(obj, fields, suffix, perms):
    """ Set group perms on an object
    To be mainly used in form operations, from which the cleaned data of fields are obtained
    Check if group is in new perms and not in old, and assign, or vice versa

    :param obj: the record object for which to get permissions
    :param fields: the permission names to categorize
    :param suffix: an additional string that, when appended on the field name, will give us the perm name
    :param perms:
    :return: a dictionary of fields: groups list
    """
    old_perms = get_perms(obj, fields, suffix)
    for field in fields:
        for group in perms[field]:
            if group not in old_perms[field]:
                assign_perm(field + suffix, group, obj)
        for group in old_perms[field]:
            if group not in perms[field]:
                remove_perm(field + suffix, group, obj)
Beispiel #41
0
 def remove_permissions(self, request, pk=None, *args, **kwargs):
     queryset = Good.objects.all()
     good = get_object_or_404(queryset, pk=pk)
     serializer = self.get_serializer(data=request.data)
     if serializer.is_valid(raise_exception=True):
         user_or_group = []
         if serializer.data['users']:
             user_or_group.extend(
                 [User.objects.get(pk=u) for u in serializer.data['users']])
         if serializer.data['groups']:
             user_or_group.extend([
                 Group.objects.get(pk=g) for g in serializer.data['groups']
             ])
         for permission in serializer.data['permissions']:
             for obj in user_or_group:
                 remove_perm(self.permission_type.get(permission), obj,
                             good)
         return Response(status=status.HTTP_200_OK)
     return Response(status=status.HTTP_400_BAD_REQUEST)
Beispiel #42
0
def setPermissionUserObject(user, object, permissions=[], mode='add'):
    """
    Assign or remove guardian permissions to user for object

    :param user: Auth user or group model obj.
    :param object: Django model obj to apply or remove permissions.
    :param permissions: Default: '[]'. A List of permission to add/remove to object for user.
    :param mode: Default: 'add'. Mode work, 'add' or 'remove'.
    :return: None
    """

    if not isinstance(permissions, list):
        permissions = [permissions]

    for perm in permissions:
        if mode == 'add':
            assign_perm(perm, user, object)
        elif mode == 'remove':
            remove_perm(perm, user, object)
Beispiel #43
0
    def assign_permissions(self):
        # Editors and users can view this algorithm
        assign_perm(f"view_{self._meta.model_name}", self.editors_group, self)
        assign_perm(f"view_{self._meta.model_name}", self.users_group, self)
        # Editors and users can execute this algorithm
        assign_perm(f"execute_{self._meta.model_name}", self.editors_group,
                    self)
        assign_perm(f"execute_{self._meta.model_name}", self.users_group, self)
        # Editors can change this algorithm
        assign_perm(f"change_{self._meta.model_name}", self.editors_group,
                    self)

        reg_and_anon = Group.objects.get(
            name=settings.REGISTERED_AND_ANON_USERS_GROUP_NAME)

        if self.public:
            assign_perm(f"view_{self._meta.model_name}", reg_and_anon, self)
        else:
            remove_perm(f"view_{self._meta.model_name}", reg_and_anon, self)
Beispiel #44
0
def assign_permissions_to_owner(*args, **kwargs):
    graph = kwargs.get("instance", None)
    raw = kwargs.get("raw", False)
    if not raw:
        if graph:
            owner = graph.owner
            aux = {'graph': graph, 'schema': graph.schema, 'data': graph.data}
            for permission_type in aux:
                for permission in PERMISSIONS[permission_type].keys():
                    assign_perm(permission, owner, aux[permission_type])
        anonymous = User.objects.get(id=settings.ANONYMOUS_USER_ID)
        if graph.public:
            for permission, obj in aux.items():
                assign_perm("view_%s" % permission, anonymous, obj)
        else:
            for permission, obj in aux.items():
                perm = "view_%s" % permission
                if anonymous.has_perm(perm, obj):
                    remove_perm(perm, anonymous, obj)
def test_user_permissions_in_resource_endpoint(api_client, resource_in_unit, user, group):
    """
    Tests that resource endpoint returns a permissions dict with correct values.
    """
    api_client.force_authenticate(user=user)

    # normal user, reservable = True
    _check_permissions_dict(api_client, resource_in_unit, is_admin=False,
                            can_make_reservations=True, can_ignore_opening_hours=False)

    # normal user, reservable = False
    resource_in_unit.reservable = False
    resource_in_unit.save()
    _check_permissions_dict(api_client, resource_in_unit, is_admin=False,
                            can_make_reservations=False, can_ignore_opening_hours=False)

    # admin, reservable = False
    user.is_general_admin = True
    user.save()
    api_client.force_authenticate(user=user)
    _check_permissions_dict(api_client, resource_in_unit, is_admin=True,
                            can_make_reservations=True, can_ignore_opening_hours=True)
    user.is_general_admin = False
    user.save()

    # user has explicit permission to make reservation
    user.groups.add(group)
    assign_perm('unit:can_make_reservations', group, resource_in_unit.unit)
    api_client.force_authenticate(user=user)
    _check_permissions_dict(api_client, resource_in_unit, is_admin=False,
                            can_make_reservations=True, can_ignore_opening_hours=False)
    remove_perm('unit:can_make_reservations', group, resource_in_unit.unit)

    resource_group = resource_in_unit.groups.create(name='rg1')
    assign_perm('group:can_make_reservations', group, resource_group)
    api_client.force_authenticate(user=user)
    _check_permissions_dict(api_client, resource_in_unit, is_admin=False,
                            can_make_reservations=True, can_ignore_opening_hours=False)

    assign_perm('unit:can_ignore_opening_hours', group, resource_in_unit.unit)
    api_client.force_authenticate(user=user)
    _check_permissions_dict(api_client, resource_in_unit, is_admin=False,
                            can_make_reservations=True, can_ignore_opening_hours=True)
Beispiel #46
0
 def setpermissions(self, lvl):
     """ Give the right groups permissions to this object
         object needs to be saved before setting perms"""
     admingroup = self.challenge.admins_group
     participantsgroup = self.challenge.participants_group
     self.persist_if_needed()
     if lvl == self.ALL:
         assign_perm("view_ComicSiteModel", admingroup, self)
         assign_perm("view_ComicSiteModel", participantsgroup, self)
     elif lvl == self.REGISTERED_ONLY:
         assign_perm("view_ComicSiteModel", admingroup, self)
         assign_perm("view_ComicSiteModel", participantsgroup, self)
     elif lvl == self.ADMIN_ONLY:
         assign_perm("view_ComicSiteModel", admingroup, self)
         remove_perm("view_ComicSiteModel", participantsgroup, self)
     else:
         raise ValueError(
             f"Unknown permissions level '{lvl}'. "
             "I don't know which groups to give permissions to this object")
Beispiel #47
0
    def test_feedback_create_restricted(self):
        '''
        Feedback create should be restricted to those with the organizations editor permission
        '''

        #setup
        decision = self.create_and_return_decision()
        #first remove the permission
        remove_perm('edit_decisions_feedback', self.betty, self.bettysorg)

        #assert that creating feedback gives a 403
        path = reverse('publicweb_feedback_create', args=[decision.id])
        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)
Beispiel #48
0
 def form_valid(self, form):
     """
     Update object-level permissions: remove all existing, then reassign.
     """
     groups_perms_dict = get_groups_with_perms(self.object,
                                               attach_perms=True)
     for group, perms_list in groups_perms_dict.items():
         for perm in perms_list:
             remove_perm(perm, group, self.object)
     assign_perm('can_manage_queue', form.cleaned_data['managing_group'],
                 self.object)
     assign_perm('can_handle_queue', form.cleaned_data['managing_group'],
                 self.object)
     assign_perm('can_view_queue', form.cleaned_data['managing_group'],
                 self.object)
     for group in form.cleaned_data['response_groups'].all():
         assign_perm('can_handle_queue', group, self.object)
         assign_perm('can_view_queue', group, self.object)
     return super().form_valid(form)
Beispiel #49
0
def remove_invitations_officer(request, stream_id, officer_id):
    stream = get_object_or_404(ProductionStream.objects.ongoing(),
                               pk=stream_id)
    checker = ObjectPermissionChecker(request.user)
    if not checker.has_perm('can_perform_supervisory_actions', stream):
        return redirect(reverse('production:production', args=(stream.id, )))

    if getattr(stream.invitations_officer, 'id', 0) == int(officer_id):
        officer = stream.invitations_officer
        stream.invitations_officer = None
        stream.save()
        if officer not in [stream.officer, stream.supervisor]:
            # Remove Officer from stream if not assigned anymore
            remove_perm('can_work_for_stream', officer.user, stream)
        messages.success(
            request, 'Invitations Officer {officer} has been removed.'.format(
                officer=officer))

    return redirect(reverse('production:production', args=(stream.id, )))
Beispiel #50
0
def manage_project(request, project_id=""):
    user = request.user
    id = project_id
    project = Project.objects.get(pk=id)
    if (user.has_perm('manage_proj', project) == False):
        raise PopupException('Sorry, you have not right to manage the project!')
    user_perms = get_users_with_perms(project, attach_perms=True)
    allusers = json.dumps(list(get_allusers()))
    page_errors = None
    if request.method == 'POST':
        for key in request.POST:
            value = request.POST[key]
        for key, value in request.POST.iteritems():
            m = re.match(r'.+_proj@', key)
            if m:
                keylist = re.split(r'@', key)
                keyperm = keylist[0]
                keyuser = User.objects.get(pk=keylist[1])
                if user_perms.has_key(keyuser):
                    if keyperm in user_perms[keyuser]:
                        user_perms[keyuser].remove(keyperm)
                    else:
                        assign_perm(keyperm, keyuser, project)
                else:
                    assign_perm(keyperm, keyuser, project)
        for key, value in user_perms.items():
            if value != []:
                for item in value:
                    remove_perm(item, key, project)
        return HttpResponseRedirect(urlresolvers.reverse('list_projects'))
    else:
        try:
            project = Project.objects.get(id=id)
        except Exception:
            raise Http404
    return render("ansible/manage_project.html", request, {
        'action': urlresolvers.reverse('manage_project', kwargs={'project_id': id}),
        'project': project,
        'user_perms': user_perms,
        'allusers': allusers,
        'page_errors': page_errors,
        'request': request,
    })
Beispiel #51
0
    def set_box_permissions(self, groups):
        permcodenames = []
        for node in Box._meta.permissions:
            permcodenames.append(node[0])

        for groupname, level in groups:
            if groupname.startswith('group-'):
                group = groupname.replace('group-', '', 1)
                group = Group.objects.get(pk=group)
                level = int(level) - 1

                if level == 0:
                    for perm in permcodenames:
                        remove_perm(perm, group, self)
                else:
                    for perm in permcodenames[:level]:
                        assign_perm(perm, group, self)
                    for perm in permcodenames[level:]:
                        remove_perm(perm, group, self)
Beispiel #52
0
def update_permission(user_or_group: Union[User, Group], obj: Model, perm: str, action: str):

    content_type = ContentType.objects.get_for_model(obj)

    # Get or create permission
    try:
        permission = Permission.objects.get(content_type=content_type, codename=perm)
    except Permission.DoesNotExist:
        name = perm.replace('_', '').title()
        permission = Permission.objects.create(
            name='Can %s %s' % (name, obj._meta.verbose_name_raw),
            content_type=content_type,
            codename=perm
        )

    if action == ACTION_ASSIGN:
        assign_perm(permission, user_or_group, obj)
    else:
        remove_perm(permission, user_or_group, obj)
Beispiel #53
0
def create_object_permissions(sender, instance, **kwargs):
    if kwargs["action"] == "pre_add":
        perms = []
        for j in kwargs["model"].objects.filter(pk__in=kwargs["pk_set"]):
            perms.extend(j.groups_allowed.all())
        for x in perms:
            assign_perm("change_" + instance.__class__.__name__.lower(), x, instance)
            assign_perm("delete_" + instance.__class__.__name__.lower(), x, instance)
    elif kwargs["action"] == "post_remove":
        perms = []
        perms_keep = []
        for j in kwargs["model"].objects.filter(pk__in=kwargs["pk_set"]):
            perms.extend(j.groups_allowed.all())
        for u in instance.collection.all():
            perms_keep.extend(u.groups_allowed.all())
        rm_perms = set(perms) - set(perms_keep)
        for x in rm_perms:
            remove_perm("change_" + instance.__class__.__name__.lower(), x, instance)
            remove_perm("delete_" + instance.__class__.__name__.lower(), x, instance)
Beispiel #54
0
    def test_unpublished_layer(self):
        """Test unpublished layer behaviour"""

        user = get_user_model().objects.get(username='******')
        self.client.login(username='******', password='******')

        # default (RESOURCE_PUBLISHING=False)
        # access to layer detail page gives 200 if layer is published or
        # unpublished
        response = self.client.get(
            reverse('layer_detail', args=('geonode:CA', )))
        self.failUnlessEqual(response.status_code, 200)
        layer = Layer.objects.filter(title='CA')[0]
        layer.is_published = False
        layer.save()
        response = self.client.get(
            reverse('layer_detail', args=('geonode:CA', )))
        self.failUnlessEqual(response.status_code, 200)

        # with resource publishing
        with self.settings(RESOURCE_PUBLISHING=True):
            # 404 if layer is unpublished
            response = self.client.get(
                reverse('layer_detail', args=('geonode:CA', )))
            self.failUnlessEqual(response.status_code, 404)
            # 200 if layer is unpublished but user has permission
            assign_perm('publish_resourcebase', user,
                        layer.get_self_resource())
            response = self.client.get(
                reverse('layer_detail', args=('geonode:CA', )))
            self.failUnlessEqual(response.status_code, 200)
            # 200 if layer is published
            layer.is_published = True
            layer.save()
            remove_perm('publish_resourcebase', user,
                        layer.get_self_resource())
            response = self.client.get(
                reverse('layer_detail', args=('geonode:CA', )))
            self.failUnlessEqual(response.status_code, 200)

        layer.is_published = True
        layer.save()
Beispiel #55
0
def change_permission(request, graph_slug):
    if request.is_ajax():
        graph = get_object_or_404(Graph, slug=graph_slug)
        user_id = request.GET['user_id']
        object_str = request.GET['object_str']
        permission_str = request.GET['permission_str']
        user = get_object_or_404(User, id=user_id)
        # Owner permissions cannot be deleted
        if user == graph.owner:
            return HttpResponse("owner", status=500)
        aux = {'graph': graph, 'schema': graph.schema, 'data': graph.data}
        if permission_str in PERMISSIONS[object_str]:
            if permission_str in guardian.get_perms(user, aux[object_str]):
                guardian.remove_perm(permission_str, user, aux[object_str])
            else:
                guardian.assign(permission_str, user, aux[object_str])
        else:
            raise ValueError("Unknown %s permission: %s" %
                             (object_str, permission_str))
    return HttpResponse(simplejson.dumps({}))
Beispiel #56
0
    def test_non_superuser_normal_site_subset_layers(self):
        """
        Test that a non superuser, that can see different layers on different sites,
        can see the correct subset of layer on a normal site
        """
        # Remove some view permissions for bobby
        anonymous_group = Group.objects.get(name='anonymous')
        for layer in Layer.objects.all()[:3]:
            remove_perm('view_resourcebase', self.bobby, layer.get_self_resource())
            remove_perm('view_resourcebase', anonymous_group, layer.get_self_resource())

        self.client.login(username='******', password='******')
        response = self.client.get(self.api_layer_url)
        self.assertEquals(len(json.loads(response.content)['objects']), 5)

        # now test with superuser
        self.client.logout()
        self.client.login(username=self.user, password=self.passwd)
        response = self.client.get(self.api_layer_url)
        self.assertEquals(len(json.loads(response.content)['objects']), 7)
Beispiel #57
0
    def set_owners(self, new_owners):
        old_owners = get_users_with_perms(self, only_with_perms_in=['owner'])

        removed_owners = []
        added_owners = []

        # Remove old owners
        for old_owner in old_owners:
            if old_owner not in new_owners:
                remove_perm('owner', old_owner, self)
                removed_owners.append(old_owner)

        # Add new owners
        for new_owner in new_owners:
            if new_owner not in old_owners:
                assign_perm('owner', new_owner, self)
                added_owners.append(new_owner)

        # Return the owners added/removed so they can be emailed
        return removed_owners, added_owners
Beispiel #58
0
    def test_groups_with_model_perms(self):
        for perm in CloudAccount.model_permissions:
            groups = shortcuts.get_groups_with_model_perms(
                CloudAccount,
                attach_perms=False,
            )

            self.assertEqual(groups.count(), 0)

            assign_perm('cloud.%s_cloudaccount' % perm, self.group)

            groups = shortcuts.get_groups_with_model_perms(
                CloudAccount,
                attach_perms=False,
            )

            self.assertEqual(groups.count(), 1)
            self.assertEqual(groups.first(), self.group)

            remove_perm('cloud.%s_cloudaccount' % perm, self.group)
Beispiel #59
0
    def _disable_owner_write_permissions(self):

        for perm in get_perms(self.resource.owner,
                              self.resource.get_self_resource()):
            remove_perm(perm, self.resource.owner,
                        self.resource.get_self_resource())

        for perm in get_perms(self.resource.owner, self.resource):
            remove_perm(perm, self.resource.owner, self.resource)

        for perm in self.resource.BASE_PERMISSIONS.get(
                'read') + self.resource.BASE_PERMISSIONS.get('download'):
            if not settings.RESOURCE_PUBLISHING and not settings.ADMIN_MODERATE_UPLOADS:
                assign_perm(perm, self.resource.owner,
                            self.resource.get_self_resource())
            elif perm not in {
                    'change_resourcebase_permissions', 'publish_resourcebase'
            }:
                assign_perm(perm, self.resource.owner,
                            self.resource.get_self_resource())
Beispiel #60
0
    def set_publication_permissions(self):
        """Sets all permissions as needed for publication.

        - removes edit, share and delete permission from everyone
        - add read permission for everyone
        """
        # Remove edit, share and delete permission from everyone
        users = get_users_with_perms(self)
        for u in users:
            for perm in ['publish_surface', 'share_surface', 'change_surface', 'delete_surface']:
                remove_perm(perm, u, self)

        # Add read permission for everyone
        assign_perm('view_surface', get_default_group(), self)

        from guardian.shortcuts import get_perms
        # TODO for unknown reasons, when not in Docker, the published surfaces are still changeable
        # Here "remove_perm" does not work. We do not allow this. See GH 704.
        if 'change_surface' in get_perms(self.creator, self):
            raise PublicationException("Withdrawing permissions for publication did not work!")