def test_direct_perms_only(self): admin = User.objects.create(username='******', is_superuser=True) self.user1.groups.add(self.group1) self.user2.groups.add(self.group1) assign_perm("change_contenttype", self.user1, self.obj1) assign_perm("delete_contenttype", admin, self.obj1) assign_perm("delete_contenttype", self.group1, self.obj1) expected = set([self.user1, self.user2, admin]) result = get_users_with_perms(self.obj1, with_superusers=False, with_group_users=True) self.assertEqual(set(result), expected) self.assertEqual(set(get_user_perms(self.user1, self.obj1)), set(['change_contenttype'])) self.assertEqual(set(get_user_perms(self.user2, self.obj1)), set([])) self.assertEqual(set(get_user_perms(admin, self.obj1)), set(['delete_contenttype'])) result = get_users_with_perms(self.obj1, with_superusers=False, with_group_users=False) expected = set([self.user1, admin]) self.assertEqual(set(result), expected) self.assertEqual(set(get_group_perms(self.user1, self.obj1)), set(['delete_contenttype'])) self.assertEqual(set(get_group_perms(self.user2, self.obj1)), set(['delete_contenttype'])) self.assertEqual(set(get_group_perms(self.group1, self.obj1)), set(['delete_contenttype'])) self.assertEqual(set(get_group_perms(self.group2, self.obj1)), set([])) self.assertEqual(set(get_group_perms(admin, self.obj1)), set([])) self.assertEqual(set(get_perms(admin, self.obj1)), set(['add_contenttype', 'change_contenttype', 'delete_contenttype'])) self.assertEqual(set(get_perms(self.user1, self.obj1)), set(['change_contenttype', 'delete_contenttype'])) self.assertEqual(set(get_perms(self.user2, self.obj1)), set(['delete_contenttype'])) self.assertEqual(set(get_perms(self.group1, self.obj1)), set(['delete_contenttype'])) self.assertEqual(set(get_perms(self.group2, self.obj1)), set([]))
def remove_all_permissions(self): """ Remove all the permissions for users and groups except for the resource owner """ # TODO refactor this # first remove in resourcebase for user, perms in get_users_with_perms(self.get_self_resource(), attach_perms=True).iteritems(): if not self.owner == user: for perm in perms: remove_perm(perm, user, self.get_self_resource()) for group, perms in get_groups_with_perms(self.get_self_resource(), attach_perms=True).iteritems(): for perm in perms: remove_perm(perm, group, self.get_self_resource()) # now remove in layer (if resource is layer if hasattr(self, "layer"): for user, perms in get_users_with_perms(self.layer, attach_perms=True).iteritems(): if not self.owner == user: for perm in perms: remove_perm(perm, user, self.layer) for group, perms in get_groups_with_perms(self.layer, attach_perms=True).iteritems(): for perm in perms: remove_perm(perm, group, self.layer)
def construct_real_group_project_ac(real_group_id, project_id, direction): if direction != 'ACTION_PTR' and direction != 'ACTION_RTP': raise PermissionDenied real_group = get_object_or_404(RealGroup, id=int(real_group_id)) project = get_object_or_404(Project, id=int(project_id)) if not RealGroup_Project_AC.objects.filter( real_group=real_group, project=project, action_code=getattr(RealGroup_Project_AC, direction), action_status=RealGroup_Project_AC.STATUS_WAIT): # ensure there's only one ac real_group_project_ac = RealGroup_Project_AC.objects.create( real_group=real_group, project=project, action_code=getattr(RealGroup_Project_AC, direction), action_status=RealGroup_Project_AC.STATUS_WAIT, ) if direction == 'ACTION_PTR': real_group_user_set = get_users_with_perms(real_group) for user in real_group_user_set: if user.has_perm('real_group_management', real_group): assign_perm( 'notification.process_real_group_project_ac', user, real_group_project_ac, ) elif direction == 'ACTION_RTP': project_user_set = get_users_with_perms(project) for user in project_user_set: if user.has_perm('project_management', project): assign_perm( 'notification.process_real_group_project_ac', user, real_group_project_ac, )
def test_attach_perms(self): self.user1.groups.add(self.group1) self.user2.groups.add(self.group2) self.user3.groups.add(self.group3) assign_perm("change_contenttype", self.group1, self.obj1) assign_perm("change_contenttype", self.group2, self.obj1) assign_perm("delete_contenttype", self.group3, self.obj2) assign_perm("delete_contenttype", self.user2, self.obj1) assign_perm("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.items(): 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.items(): self.assertEqual(set(perms), set(expected[key]))
def test_empty(self): result = get_users_with_perms(self.flatpage1) self.assertTrue(isinstance(result, QuerySet)) self.assertEqual(list(result), []) result = get_users_with_perms(self.flatpage1, attach_perms=True) self.assertTrue(isinstance(result, dict)) self.assertFalse(bool(result))
def _set_ac_process_perm(self): real_group = self.ac.real_group project = self.ac.project # assign perm to real group's manager for user in get_users_with_perms(real_group): if user.has_perm('group_management', real_group): self._assign_perm(user) # assign perm to project's manager for user in get_users_with_perms(project): if user.has_perm('project_management', project): self._assign_perm(user)
def finRevisionItem(request, id_item): """ *Función para Finalizar de un ítem que ha entrado en una estado de Revision. Obs. Solo el Lider de Proyecto puede realizar esta operación. * :param request: HttpRequest necesario para visualizar las versiones de un ítem, es la solicitud de la acción. :param id_fase: Identificador de la fase dentro del proyecto a la cual pertenece el ítem. :param id_item: Identificador del Item al cual se esta consultando su historial de versiones :param args: Argumentos para el modelo ``Item``. :param kwargs: Keyword Arguments para la el modelo ``Item``. :return: Regresa una lista de todos los ítems, con el ítem finalizado correctamente e incluido nuevamente en la Base de Datos. """ item = ItemBase.objects.get(pk=id_item) mensajes = [] usuarios = get_users_with_perms(item) if usuarios.count() == 0 or request.user in usuarios: remove_perm('credencial', request.user, item) item.estado = 'ELB' item.save() usuarios = get_users_with_perms(item) if usuarios.count() == 0: solicitudes = SolicitudCambios.objects.filter(usuario=request.user, estado='ACP', items=item) if solicitudes.count() > 0: solicitud = solicitudes[0] items_solicitud = solicitud.items.all() finalizado = True for item in items_solicitud: permisos = get_perms(request.user, item) if 'credencial' in permisos: finalizado = False if finalizado: solicitud.estado = 'EJC' solicitud.save() message = 'Revision Finalizada para el Item:' + item.nombre error = 0 mensajes.append(message) request.session['messages'] = mensajes request.session['error'] = error else: message = 'No se puede terminar la revision, aún existen usuarios trabajando en el item.' error = 1 mensajes.append(message) request.session['messages'] = mensajes request.session['error'] = error return HttpResponseRedirect(reverse('administrarFases.views.workphase', kwargs={'id_fase': item.tipoitem.fase_id}))
def test_direct_perms_only(self): admin = User.objects.create(username='******', is_superuser=True) self.user1.groups.add(self.group1) self.user2.groups.add(self.group1) assign_perm("change_contenttype", self.user1, self.obj1) assign_perm("delete_contenttype", admin, self.obj1) assign_perm("delete_contenttype", self.group1, self.obj1) # With direct_perms_only=False (default) expected = set([self.user1, self.user2, admin]) result = get_users_with_perms(self.obj1) self.assertEqual(set(result), expected) # With direct_perms_only=True result = get_users_with_perms(self.obj1, direct_perms_only=True) expected = set([self.user1, admin]) self.assertEqual(set(result), expected)
def get_object(self, *args, **kwargs): """Return the Config associated with the App's latest Release.""" app = get_object_or_404(models.App, id=self.kwargs['id']) user = self.request.user if user == app.owner or user in get_users_with_perms(app): return app.release_set.latest().config raise PermissionDenied()
def retrieve(self, request, pk): """ Return a list of Users with permissions on given CheckList """ if not request.user.is_authenticated(): return Response( status=403, data={ 'detail': 'Authentication required', }, ) 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', }, ) users = get_users_with_perms(check_list) serializer = UserSerializer(users, many=True, ) return Response(serializer.data)
def construct_user_real_group_ac(user_info_id, real_group_id, direction): if direction != 'ACTION_RTU' and direction != 'ACTION_UTR': raise PermissionDenied user_info = get_object_or_404(UserInfo, id=int(user_info_id)) real_group = get_object_or_404(RealGroup, id=int(real_group_id)) if not UserInfo_RealGroup_AC.objects.filter( user_info=user_info, real_group=real_group, action_code=getattr(UserInfo_RealGroup_AC, direction), action_status=UserInfo_RealGroup_AC.STATUS_WAIT): # ensure there's only one ac real_group_user_ac = UserInfo_RealGroup_AC.objects.create( user_info=user_info, real_group=real_group, action_code=getattr(UserInfo_RealGroup_AC, direction), action_status=UserInfo_RealGroup_AC.STATUS_WAIT, ) if direction == 'ACTION_RTU': assign_perm( 'notification.process_user_real_group_ac', user_info.user, real_group_user_ac, ) else: real_group_user_set = get_users_with_perms(real_group) for user in real_group_user_set: if user.has_perm('real_group_management', real_group): assign_perm( 'notification.process_user_real_group_ac', user, real_group_user_ac )
def test_without_group_users_no_result(self): self.user1.groups.add(self.group1) assign_perm("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)
def get_all_level_info(self): resource = self.get_self_resource() info = {'users': {}, 'groups': {}} users = get_users_with_perms( resource, attach_perms=True, with_superusers=True) groups = get_groups_with_perms( resource, attach_perms=True) # add the creator even if they have no permissions if self.creator not in users: users[self.creator] = [] # add the applications that needs this resource # even if they have no permissions typ = None if hasattr(self, 'layer') and self.layer.layer_type is not None: typ = self.layer.layer_type.name elif hasattr(self, 'tabular') and self.tabular.tabular_type is not None: typ = self.tabular.tabular_type.name if typ is not None: for app in App.objects.filter(keywords__name=typ): ego = app.get_alter_ego() if ego is not None and ego not in users: users[ego] = [] info['users'] = users info['groups'] = groups return info
def get_context_data(self, **kwargs): context = super(LandingView, self).get_context_data(**kwargs) context['channel'] = get_objects_for_user(self.request.user, 'mumblecast.edit_channel') if self.request.user.is_superuser: for c in context["channel"]: c.users = get_users_with_perms(c) return context
def get_collaborators(self, include_anonymous=False): all_collaborators = get_users_with_perms(self) if include_anonymous: return list(all_collaborators.exclude(id=self.owner.id)) else: return list(all_collaborators.exclude(id__in=[self.owner.id, settings.ANONYMOUS_USER_ID]))
def reset_permissions(self): users = get_users_with_perms(self) for user in users: self.delete_all_permissions(user) groups = get_groups_with_perms(self) for group in groups: self.delete_all_permissions(group)
def delete_attachment(request, id): attachment = get_object_or_404(Attachment, id=id) problem = attachment.problem checker = ObjectPermissionChecker(request.user) if not checker.has_perm('edit_problem', problem) and problem.user != request.user: raise Http404 old_id = attachment.id old_filename = attachment.file.name attachment.file.delete(False) attachment.delete() # 해당 오브젝트에 대해 아무 퍼미션이나 있으면 처리됨. 문제의 경우 PUBLISHED 일 때는 이 권한을 사용하지 않아서 안전하다 visible_users = get_users_with_perms(problem, with_group_users=False) visible_groups = get_groups_with_perms(problem) publish("problem-attachment-delete-%s" % datetime.now().strftime('%s.%f'), "problem", "problem-attachment", actor=request.user, target=problem, timestamp=datetime.now(), visible_users=visible_users, visible_groups=visible_groups, verb=u"문제 {target}에서 첨부파일 %s 을 삭제했습니다." % os.path.basename(old_filename)) return HttpResponse("[]")
def get_users_with_perm(obj, perm): data = get_users_with_perms(obj, attach_perms=True) r = [] for user, perms in data.iteritems(): if perm in perms: r.append(user) return r
def get_owner(self): # ownership is determined by "add" permission user_permissions = get_users_with_perms(self, attach_perms=True, with_group_users=False) for user, permission in user_permissions.iteritems(): if "add_%s" % self._meta.verbose_name in permission: return user return None
def calculate(self): """Return a representation for configuration management""" d = {} d['id'] = self.id d['release'] = {} releases = self.release_set.all().order_by('-created') if releases: release = releases[0] d['release']['version'] = release.version d['release']['config'] = release.config.values d['release']['build'] = {'image': release.build.image} if release.build.url: d['release']['build']['url'] = release.build.url d['release']['build']['procfile'] = release.build.procfile d['containers'] = {} containers = self.container_set.all() if containers: for c in containers: d['containers'].setdefault(c.type, {})[str(c.num)] = c.status d['domains'] = [] if self.formation.domain: d['domains'].append('{}.{}'.format(self.id, self.formation.domain)) else: for n in self.formation.node_set.filter(layer__proxy=True): d['domains'].append(n.fqdn) # add proper sharing and access controls d['users'] = {self.owner.username: '******'} for u in (get_users_with_perms(self)): d['users'][u.username] = 'user' return d
def test_without_group_users_no_result_but_with_superusers(self): admin = User.objects.create(username="******", is_superuser=True) self.user1.groups.add(self.group1) assign_perm("change_contenttype", self.group1, self.obj1) result = get_users_with_perms(self.obj1, with_group_users=False, with_superusers=True) expected = [admin] self.assertEqual(set(result), set(expected))
def validate_permission(self, user_or_group, class_permission_key): def name(user_or_group): if isinstance(user_or_group, Group): return "Group {group_name}".format(group_name=user_or_group.name) else: user_groups = [g.name for g in user_or_group.groups.all()] if user_groups: user_groups_string = ', '.join() else: user_groups_string = '(No groups)' return "User {username} of groups {groups}".format(username=user_or_group.username, groups=user_groups_string) if not user_or_group.has_perm(class_permission_key, self): raise Exception( "%s lacks expected permission key %s to instance %s.\nThe user has permission to the following \ instances %s.\nThe user is a member of the following groups: %s.\nThe object permits the \ following groups: %s,\nand the following users: %s" % ( name(user_or_group), class_permission_key, self.name, ', '.join(ObjectPermissionChecker(user_or_group).get_perms(self)), ', '.join(map(lambda group: group.name, user_or_group.groups.all() if not isinstance(user_or_group, Group) else [])), ', '.join(map(lambda user_group: name(user_group), list(get_groups_with_perms(self)))), ', '.join(map(lambda user_group: name(user_group), list(get_users_with_perms(self))))) )
def granular_perms_detail(request, contenttype_id, object_id): if not request.user.is_staff: raise Http404 content_type = get_object_or_404(ContentType, pk=contenttype_id) model = content_type.model_class() try: obj = content_type.get_object_for_this_type(pk=object_id) except model.DoesNotExist(): raise Http404 if not isinstance(obj, GranularPermissionedModel): raise Http404 actors = list(Group.objects.all()) anonymous = get_anonymous_user() # adding anonymous user actors.append(anonymous) # adding users with custom permissions # (excluding anonymous user from this qs) actors += list(get_users_with_perms(obj, with_group_users=False).exclude(pk=anonymous.id)) return TemplateResponse(request, 'core/perms/granular_detail.html', { 'model': model, 'perms_to_check': model._meta.permissions, 'actors': actors, 'object': obj, 'obj_ct_id': contenttype_id, })
def test_attach_groups_only_has_perms(self): cache.clear() self.user1.groups.add(self.group1) assign_perm("change_contenttype", self.group1, self.obj1) result = get_users_with_perms(self.obj1, attach_perms=True) expected = {self.user1: ["change_contenttype"]} self.assertEqual(result, expected)
def get_all_level_info(self): resource = self.get_self_resource() info = { 'users': get_users_with_perms(resource, attach_perms=True, with_superusers=True), 'groups': get_groups_with_perms(resource, attach_perms=True) } return info
def list(self, request, **kwargs): app = get_object_or_404(self.model, id=kwargs["id"]) perm_name = "api.{}".format(self.perm) if request.user != app.owner and not request.user.has_perm(perm_name, app): return Response(status=status.HTTP_403_FORBIDDEN) usernames = [u.username for u in get_users_with_perms(app) if u.has_perm(perm_name, app)] return Response({"users": usernames})
def _get_group_users_with_perms(obj, attach_perms=False, user_perms=None): """ Returns a list of users in the groups with permissions on the object obj. """ group_obj_perms = get_group_perms(obj) if group_obj_perms is None: return get_users_with_perms( obj, attach_perms=attach_perms, with_group_users=True) group_users = {} if attach_perms: if user_perms: group_users.update(user_perms) _cache = {} for perm in group_obj_perms: if perm.group not in _cache: _cache[perm.group] = perm.group.user_set.all() for user in _cache[perm.group]: if user in group_users: group_users[user].add(perm.permission.codename) else: group_users[user] = set([perm.permission.codename]) else: group_users = set() if not user_perms else set(user_perms) for perm in group_obj_perms.distinct('group'): group_users.union( set([user for user in perm.group.user_set.all()])) group_users = list(group_obj_perms) return group_users
def form_valid(self, form): response = super(SetPermissionsView, self).form_valid(form) obj = self.get_object() obj_type = self.get_object_type(obj) users_old = set(get_users_with_perms(self.get_object())) users = set(form.cleaned_data['users']) if form.cleaned_data['who_can_change'] == 'everyone': # Clear out all users del_users = users_old add_users = [] else: del_users = users_old - users add_users = users - users_old for u in add_users: assign_perm('change_%s' % obj_type, u, obj) assign_perm('add_%s' % obj_type, u, obj) assign_perm('delete_%s' % obj_type, u, obj) for u in del_users: remove_perm('change_%s' % obj_type, u, obj) remove_perm('add_%s' % obj_type, u, obj) remove_perm('delete_%s' % obj_type, u, obj) messages.add_message(self.request, messages.SUCCESS, _("Permissions updated!")) return response
def go(): problem = get_or_none(Problem, id=id) if not problem: return {"success": False, "error": u"존재하지 않는 문제입니다."} checker = ObjectPermissionChecker(request.user) if not checker.has_perm('edit_problem', problem) and problem.user != request.user: return {"success": False, "error": u"권한이 없습니다."} if request.method != "POST": return {"success": False, "error": u"POST 접근하셔야 합니다."} file = request.FILES["file"] md5 = md5file(file) target_path = os.path.join("judge-attachments", md5, file.name) storage = DefaultStorage() storage.save(target_path, file) new_attachment = Attachment(problem=problem, file=target_path) new_attachment.save() # 해당 오브젝트에 대해 아무 퍼미션이나 있으면 처리됨. 문제의 경우 PUBLISHED 일 때는 이 권한을 사용하지 않아서 안전하다 visible_users = get_users_with_perms(problem, with_group_users=False) visible_groups = get_groups_with_perms(problem) publish("problem-attachment-%s" % datetime.now().strftime('%s.%f'), "problem", "problem-attachment", actor=request.user, target=problem, timestamp=datetime.now(), visible_users=visible_users, visible_groups=visible_groups, verb=u"문제 {target}에 첨부파일 %s 을 추가했습니다." % file.name) return {"success": True}
def get_detailed_project_permissions(current_user, project): """ Builds up a list of users and permissions for the project. { username: "", display_name: "", permissions: "" } """ permission_table = [] # ignore permissions for those in the public group users = get_users_with_perms(project, with_group_users=False) for user in users: display_name = user.first_name + " " + user.last_name # ignore the current user if user != current_user: permission_table.append({ "username": user.username, "display_name": display_name, "permissions": get_perms(user, project) }) return permission_table
def test_request_confirm_decline_flow(django_app, volunteer, planner, event): # decline a participation as volunteer assert volunteer in get_users_with_perms(event, only_with_perms_in=["view_event"]) response = django_app.get(event.get_absolute_url(), user=volunteer) response.form.submit(name="signup_choice", value="decline") shift = event.shifts.first() assert (LocalParticipation.objects.get( user=volunteer, shift=shift).state == AbstractParticipation.States.USER_DECLINED) response = django_app.get(event.get_absolute_url(), user=volunteer) assert "already declined" in response
def get_initial(self, *args, **kwargs): initial = super().get_initial(*args, **kwargs) forum = get_object_or_404(Forum, slug=self.kwargs.get('slug')) voters = get_users_with_perms(forum) ineligible_ids = [] for voter in voters.all(): if not voter.has_perm('can_post_to_forum', forum): ineligible_ids.append(voter.id) initial.update({ 'eligible_for_voting': voters.exclude(id__in=ineligible_ids), }) return initial
def test_phase_permissions(self): """Only challenge admins should be able to view and change phases.""" p: Phase = PhaseFactory() assert get_groups_with_set_perms(p) == { p.challenge.admins_group: { "change_phase", "view_phase", "create_phase_submission", }, p.challenge.participants_group: {"create_phase_submission"}, } assert get_users_with_perms(p, with_group_users=False).count() == 0
def test_get_users_with_perms_plus_groups(self): User.objects.create_user('john', '*****@*****.**', 'john') jane = User.objects.create_user('jane', '*****@*****.**', 'jane') group = Group.objects.create(name='devs') self.joe.groups.add(group) assign_perm('add_project', self.joe, self.project) assign_perm('change_project', group, self.project) assign_perm('change_project', jane, self.project) self.assertEqual( get_users_with_perms(self.project, attach_perms=True), { self.joe: ['add_project', 'change_project'], jane: ['change_project'], })
def test_create_event(django_app, planner, superuser, service_event_type, groups): managers, planners, volunteers = groups event_form = django_app.get( reverse("core:event_create", kwargs=dict(type=service_event_type.pk)), user=planner, ).form event_form["title"] = "Seeed Concert" event_form["description"] = "when at location, call 0123456789" event_form["location"] = "BOS ARENA" event_form["mail_updates"] = True event_form["visible_for"] = [volunteers.id] event_form["responsible_groups"] = [planners.id] # event_form["responsible_users"] is prefilled with planner shift_form = event_form.submit().follow().form shift_form["date"] = date.today() shift_form["meeting_time"] = time(9, 0) shift_form["start_time"] = time(10, 0) shift_form["end_time"] = time(16, 0) event = shift_form.submit().follow().context["event"] assert event.title == "Seeed Concert" assert set(get_groups_with_perms(event, only_with_perms_in=["view_event"])) == { volunteers, planners, } assert set( get_groups_with_perms(event, only_with_perms_in=["change_event" ])) == {planners} assert set( get_users_with_perms(event, only_with_perms_in=["change_event"], with_group_users=False)) == {planner} assert set(get_users_with_perms(event, only_with_perms_in=["change_event"])) == { planner, superuser, } # superuser is in planner group
def get_users_with_perm(self, permission): anyperm = get_users_with_perms(self.get_object().collection, attach_perms=True, with_superusers=False) result = User.objects.filter(is_superuser=True).all() for user, perms in anyperm.iteritems(): if permission in perms: result = chain(result, User.objects.filter(username=user)) result = list(result) return result
def get_permission_users(self, request, pk=None, *args, **kwargs): queryset = Good.objects.all() good = get_object_or_404(queryset, pk=pk) users = get_users_with_perms(good, attach_perms=True, with_group_users=False) serializer = self.get_serializer([{ 'id': u.id, 'name': u.username, 'pers': p } for u, p in users.items()], many=True) return Response(serializer.data)
def test_direct_perms_only_perms_attached(self): admin = User.objects.create(username='******', is_superuser=True) self.user1.groups.add(self.group1) self.user2.groups.add(self.group1) assign_perm("change_contenttype", self.user1, self.obj1) assign_perm("delete_contenttype", admin, self.obj1) assign_perm("delete_contenttype", self.group1, self.obj1) expected = { self.user1: ["change_contenttype", "delete_contenttype"], admin: ["add_contenttype", "change_contenttype", "delete_contenttype"], self.user2: ["delete_contenttype"] } result = get_users_with_perms(self.obj1, attach_perms=True, with_superusers=False, with_group_users=True) self.assertEqual(result.keys(), expected.keys()) for key, perms in result.items(): self.assertEqual(set(perms), set(expected[key])) result = get_users_with_perms(self.obj1, attach_perms=True, with_superusers=False, with_group_users=False) expected = {self.user1: ["change_contenttype"], admin: ["delete_contenttype"]} self.assertEqual(result, expected)
def get_restricted_users(resource): """ Takes a resource instance and identifies which users are explicitly restricted from reading, editing, deleting, or accessing it. """ user_perms = get_users_with_perms(resource, attach_perms=True, with_group_users=False) user_and_group_perms = get_users_with_perms(resource, attach_perms=True, with_group_users=True) result = { "no_access": [], "cannot_read": [], "cannot_write": [], "cannot_delete": [], } for user, perms in user_and_group_perms.items(): if user.is_superuser: pass elif user in user_perms and "no_access_to_resourceinstance" in user_perms[ user]: for k, v in result.items(): v.append(user.id) else: if "view_resourceinstance" not in perms: result["cannot_read"].append(user.id) if "change_resourceinstance" not in perms: result["cannot_write"].append(user.id) if "delete_resourceinstance" not in perms: result["cannot_delete"].append(user.id) if "no_access_to_resourceinstance" in perms and len(perms) == 1: result["no_access"].append(user.id) return result
def get_recipients_for_site(site): """ Returns mails and sms of users with allowance to recieve messages for site """ users = get_users_with_perms(site) mails = [] sms_numbers = [] for user in users: mails.append(user.email) if user.on_call and user.send_sms and user.phone_number: sms_numbers.append(user.phone_number) return mails, sms_numbers
def test_only_with_perms(self): assign_perm("change_contenttype", self.user1, self.obj1) assign_perm("delete_contenttype", self.user2, self.obj1) assign_perm("delete_contenttype", self.user3, self.obj2) result = get_users_with_perms(self.obj1, only_with_perms=('change_contenttype', )) result_vals = result.values_list('username', flat=True) self.assertEqual( set(result_vals), set((self.user1.username, )), )
def update_group(self, group_name, user_list): if group_name not in Project.get_read_permission_groups(): raise ValueError(f'Error: {group_name} is not a valid group on this Project.') old_list = get_users_with_perms(self, only_with_perms_in=[group_name]) for previously_permitted_user in old_list: if previously_permitted_user.username not in user_list: remove_perm(group_name, previously_permitted_user, self) for username in user_list: new_permitted_user = User.objects.get(username=username) if new_permitted_user not in old_list: assign_perm(group_name, new_permitted_user, self)
def create(self, request, *args, **kwargs): app = get_object_or_404(models.App, id=request.DATA['receive_repo']) user = get_object_or_404(User, username=request.DATA['receive_user']) # check the user is authorized for this app if user == app.owner or \ user in get_users_with_perms(app) or \ user.is_superuser: request._data = request.DATA.copy() request.DATA['app'] = app request.DATA['owner'] = user return super(PushHookViewSet, self).create(request, *args, **kwargs) raise PermissionDenied()
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) helper = PrefixHelper(self.request.user, self.object.volume, self.object.prefix) helper.collect(max_levels=1) context['breadcrumbs'] = helper.get_breadcrumbs() context['users_perms'] = OrderedDict( sorted(get_users_with_perms(self.object, attach_perms=True, with_group_users=False).items(), key=lambda user: user[0].username)) context['model_perms'] = get_perms_for_model(self.object.__class__) return context
def test_submission_permissions(self): """ Challenge admins and submission creators should be able to view submissions. """ s: Submission = SubmissionFactory() assert get_groups_with_set_perms(s) == { s.phase.challenge.admins_group: {"view_submission"} } assert get_users_with_perms( s, attach_perms=True, with_group_users=False ) == {s.creator: ["view_submission"]}
def obj_perms_manage_view(self, request, object_pk): """ Main object permissions view. Presents all users and groups with any object permissions for the current model *instance*. Users or groups without object permissions for related *instance* would **not** be shown. In order to add or manage user or group one should use links or forms presented within the page. """ obj = get_object_or_404(self.queryset(request), pk=object_pk) users_perms = SortedDict( get_users_with_perms(obj, attach_perms=True, with_group_users=False)) users_perms.keyOrder.sort(key=lambda user: user.username) groups_perms = SortedDict(get_groups_with_perms(obj, attach_perms=True)) groups_perms.keyOrder.sort(key=lambda group: group.name) if request.method == 'POST' and 'submit_manage_user' in request.POST: user_form = UserManage(request.POST) group_form = GroupManage() info = (self.admin_site.name, self.model._meta.app_label, self.model._meta.module_name) if user_form.is_valid(): user_id = user_form.cleaned_data['user'].id url = reverse('%s:%s_%s_permissions_manage_user' % info, args=[obj.pk, user_id]) return redirect(url) elif request.method == 'POST' and 'submit_manage_group' in request.POST: user_form = UserManage() group_form = GroupManage(request.POST) info = (self.admin_site.name, self.model._meta.app_label, self.model._meta.module_name) if group_form.is_valid(): group_id = group_form.cleaned_data['group'].id url = reverse('%s:%s_%s_permissions_manage_group' % info, args=[obj.pk, group_id]) return redirect(url) else: user_form = UserManage() group_form = GroupManage() context = self.get_obj_perms_base_context(request, obj) context['users_perms'] = users_perms context['groups_perms'] = groups_perms context['user_form'] = user_form context['group_form'] = group_form return render_to_response( self.get_obj_perms_manage_template(), context, RequestContext(request, current_app=self.admin_site.name))
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, })
def comment_handler(sender, **kwargs): instance, created = kwargs["instance"], kwargs["created"] profile = instance.user.get_profile() target = instance.content_object ctype = ContentType.objects.get_for_model(target) visible_users = None visible_groups = None if ctype.name == 'post': print 'post' print target.category visible_users = get_users_with_perms(target.category, with_group_users=False) visible_groups = get_groups_with_perms(target.category) if ctype.name == 'problem' and target.state != Problem.PUBLISHED: visible_users = get_users_with_perms(target, with_group_users=False) visible_groups = get_groups_with_perms(target) print visible_users print visible_groups if created: publish("comment-%d" % instance.id, "posts", "commented", actor=instance.user, action_object=instance, target=target, timestamp=instance.submit_date, visible_users=visible_users, visible_groups=visible_groups, verb=u"{target}에 새 댓글을 달았습니다: " u"{action_object}") profile.posts += 1 elif instance.is_removed: depublish("comment-%d" % instance.id) profile.posts -= 1 profile.save()
def test_mixed(self): self.user1.groups.add(self.group1) assign_perm("change_contenttype", self.group1, self.obj1) assign_perm("change_contenttype", self.user2, self.obj1) assign_perm("delete_contenttype", self.user2, self.obj1) assign_perm("delete_contenttype", self.user2, self.obj2) assign_perm("change_contenttype", self.user3, self.obj2) assign_perm("change_%s" % user_module_name, self.user3, self.user1) result = get_users_with_perms(self.obj1) self.assertEqual( set(result), set([self.user1, self.user2]), )
def remove_all_permissions(self): """ Remove all the permissions for users and groups except for the resource owner """ for user, perms in get_users_with_perms(self.get_self_resource(), attach_perms=True).iteritems(): if not self.owner == user: for perm in perms: remove_perm(perm, user, self.get_self_resource()) for group, perms in get_groups_with_perms( self.get_self_resource(), attach_perms=True).iteritems(): for perm in perms: remove_perm(perm, group, self.get_self_resource())
def test_users_groups_perms(self): self.user1.groups.add(self.group1) self.user2.groups.add(self.group2) self.user3.groups.add(self.group3) assign_perm("change_contenttype", self.group1, self.obj1) assign_perm("change_contenttype", self.group2, self.obj1) assign_perm("delete_contenttype", self.group3, self.obj2) result = get_users_with_perms(self.obj1).values_list('pk', flat=True) self.assertEqual( set(result), set([u.pk for u in (self.user1, self.user2)]) )
def test_get_users_with_perms_plus_groups(self): User.objects.create_user('john', '*****@*****.**', 'john') jane = User.objects.create_user('jane', '*****@*****.**', 'jane') group = Group.objects.create(name='devs') self.joe.groups.add(group) assign_perm('add_mixed', self.joe, self.mixed) assign_perm('change_mixed', group, self.mixed) assign_perm('change_mixed', jane, self.mixed) self.assertEqual(get_users_with_perms(self.mixed, attach_perms=True), { self.joe: ['add_mixed', 'change_mixed'], jane: ['change_mixed'], }) result = get_objects_for_user(self.joe, 'testapp.add_mixed') self.assertEqual(sorted(p.pk for p in result), sorted([self.mixed.pk]))
def test_only_with_perms_attached(self): assign_perm("change_contenttype", self.user1, self.obj1) assign_perm("change_contenttype", self.user2, self.obj1) assign_perm("delete_contenttype", self.user2, self.obj1) assign_perm("delete_contenttype", self.user3, self.obj2) result = get_users_with_perms(self.obj1, only_with_perms=('delete_contenttype', ), attach_perms=True) expected = {self.user2: ('change_contenttype', 'delete_contenttype')} self.assertEqual(result.keys(), expected.keys()) for key, perms in result.items(): self.assertEqual(set(perms), set(expected[key]))
def email_participants(request,share,subdir=None): try: subject = request.POST.get('subject') emails = request.POST.getlist('emails',[]) users = [u for u in get_users_with_perms(share, attach_perms=False, with_superusers=False, with_group_users=True)] if len(emails) > 0: users = [u for u in User.objects.filter(id__in=[u.id for u in users]).filter(email__in=emails)] body = request.POST.get('body') users.append(share.owner) email_users(users, ctx_dict={}, subject=subject, body=body,from_email=request.user.email,content_subtype='plain') response = {'status':'success','sent_to':[u.email for u in users]} return json_response(response) except Exception, e: return JsonResponse({'errors':[str(e)]},status=400)
def graph_collaborators(request, graph_slug): # Only graph owner should be able to do this graph = get_object_or_404(Graph, slug=graph_slug) if request.user != graph.owner: return redirect('%s?next=%s' % (reverse("signin"), request.path)) users = User.objects.all().exclude(pk=settings.ANONYMOUS_USER_ID) all_collaborators = guardian.get_users_with_perms(graph) collaborators = list( all_collaborators.exclude( id__in=[request.user.id, settings.ANONYMOUS_USER_ID])) if request.POST: data = request.POST.copy() form = AddCollaboratorForm(data=data, graph=graph, collaborators=collaborators) if form.is_valid(): user_id = form.cleaned_data["new_collaborator"] user = get_object_or_404(User, id=user_id) guardian.assign('view_graph', user, graph) collaborators.append(user) else: form = AddCollaboratorForm(graph=graph, collaborators=collaborators) graph_permissions = guardian.get_perms_for_model(graph) permissions_list = [] permissions_table = [] aux = (('graph', graph), ('schema', graph.schema), ('data', graph.data)) for item in aux: for p in PERMISSIONS[item[0]].values(): permissions_list.append(p) for user in collaborators: permission_row = {} permission_row['user_id'] = user.id permission_row['user_name'] = user.username permission_row['perms'] = [] for item_str, item_obj in aux: user_permissions = guardian.get_perms(user, item_obj) for p in PERMISSIONS[item_str].keys(): if p in user_permissions: permission_row['perms'].append((item_str, p, True)) else: permission_row['perms'].append((item_str, p, False)) permissions_table.append(permission_row) #users = [u for u in users if u != graph.owner and u not in collaborators] return render_to_response('graphs_collaborators.html', { "graph": graph, "permissions": permissions_list, "permissions_table": permissions_table, "form": form }, context_instance=RequestContext(request))
def get_collaborators(self, include_anonymous=False, as_queryset=False): all_collaborators = get_users_with_perms(self) if include_anonymous: if as_queryset: return all_collaborators.exclude(id=self.owner.id) else: return list(all_collaborators.exclude(id=self.owner.id)) else: if as_queryset: return all_collaborators.exclude(id__in=[self.owner.id, settings.ANONYMOUS_USER_ID]) else: return list(all_collaborators.exclude( id__in=[self.owner.id, settings.ANONYMOUS_USER_ID]))
def __init__(self, *args, **kwargs): User = get_user_model() cost_centre = kwargs.pop('cost_centre') administering_user = kwargs.pop('user') users_with_permission = get_users_with_perms(cost_centre, attach_perms=True) id_list = [user.id for user in users_with_permission] id_list.append(administering_user.id) super(RemovePermissionAdminForm, self).__init__(*args, **kwargs) self.fields['users'].queryset = User.objects.filter( pk__in=id_list ).exclude(pk=administering_user.id)
def get_object_users_with_permissions(obj): """Returns users, roles and permissions for a object. """ users_with_perms = [] if obj: users_with_perms = [{ 'user': user, 'role': get_role(permissions, obj), 'permissions': permissions } for user, permissions in get_users_with_perms( obj, attach_perms=True, with_group_users=False).items()] return users_with_perms
def test_algorithm_evaluation_permissions(self): """ Only the challenge admins should be able to view algorithm evaluations The submission creator, algorithm groups and participants should not have view permissions """ j = AlgorithmJobFactory() assert get_groups_with_set_perms(j) == {j.viewers: {"view_job"}} assert get_users_with_perms(j, attach_perms=True, with_group_users=False) == { j.creator: ["change_job"] }
def get(self, request, organization_slug): organization = get_object_or_404(Organization, slug=organization_slug) leagues = League.objects.filter(organization=request.user.organization) # Get all users with admin privileges for this organization. organization_permissions_filtered = [] for permission in get_perms_for_model(Organization): if permission.codename not in settings.RINK_PERMISSIONS_IGNORE: organization_permissions_filtered.append(permission.codename) organization.users = get_users_with_perms( organization, attach_perms=True, only_with_perms_in=organization_permissions_filtered, ) # Get all users with admin priveleges for all leagues under this # organization. league_permissions_filtered = [] for permission in get_perms_for_model(League): if permission.codename not in settings.RINK_PERMISSIONS_IGNORE: league_permissions_filtered.append(permission.codename) for league in leagues: league.users = get_users_with_perms( league, attach_perms=True, only_with_perms_in=league_permissions_filtered) return render( request, 'league/permissions_list.html', { 'organization': organization, 'leagues': leagues, 'ignore': settings.RINK_PERMISSIONS_IGNORE, })