Esempio n. 1
0
    def get_all_level_info(self):

        resource = self.get_self_resource()
        info = {
            'users': get_users_with_perms(
                resource),
            'groups': get_groups_with_perms(
                resource,
                attach_perms=True)}

        # TODO very hugly here, but isn't huglier
        # to set layer permissions to resource base?
        if hasattr(self, "layer"):
            info_layer = {
                'users': get_users_with_perms(
                    self.layer),
                'groups': get_groups_with_perms(
                    self.layer,
                    attach_perms=True)}

            for user in info_layer['users']:
                if user in info['users']:
                    info['users'][user] = info['users'][user] + info_layer['users'][user]
                else:
                    info['users'][user] = info_layer['users'][user]

            for group in info_layer['groups']:
                if group in info['groups']:
                    info['groups'][group] = info['groups'][group] + info_layer['groups'][group]
                else:
                    info['groups'][group] = info_layer['groups'][group]

        return info
Esempio n. 2
0
    def get_all_level_info(self):

        resource = self.get_self_resource()
        info = {
            'users': get_users_with_perms(resource),
            'groups': get_groups_with_perms(resource, attach_perms=True)
        }

        # TODO very hugly here, but isn't huglier
        # to set layer permissions to resource base?
        if hasattr(self, "layer"):
            info_layer = {
                'users': get_users_with_perms(self.layer),
                'groups': get_groups_with_perms(self.layer, attach_perms=True)
            }

            for user in info_layer['users']:
                if user in info['users']:
                    info['users'][
                        user] = info['users'][user] + info_layer['users'][user]
                else:
                    info['users'][user] = info_layer['users'][user]

            for group in info_layer['groups']:
                if group in info['groups']:
                    info['groups'][group] = info['groups'][group] + info_layer[
                        'groups'][group]
                else:
                    info['groups'][group] = info_layer['groups'][group]

        return info
Esempio n. 3
0
    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)
Esempio n. 4
0
    def get_all_level_info(self):
        resource = self.get_self_resource()
        users = get_users_with_perms(resource)
        groups = get_groups_with_perms(resource, attach_perms=True)
        if groups:
            for group in groups:
                try:
                    group_profile = GroupProfile.objects.get(slug=group.name)
                    managers = group_profile.get_managers()
                    if managers:
                        for manager in managers:
                            if manager not in users and not manager.is_superuser and \
                            manager != resource.owner:
                                for perm in ADMIN_PERMISSIONS + VIEW_PERMISSIONS:
                                    assign_perm(perm, manager, resource)
                                users[
                                    manager] = ADMIN_PERMISSIONS + VIEW_PERMISSIONS
                except GroupProfile.DoesNotExist:
                    pass
        if resource.group:
            try:
                group_profile = GroupProfile.objects.get(
                    slug=resource.group.name)
                managers = group_profile.get_managers()
                if managers:
                    for manager in managers:
                        if manager not in users and not manager.is_superuser and \
                        manager != resource.owner:
                            for perm in ADMIN_PERMISSIONS + VIEW_PERMISSIONS:
                                assign_perm(perm, manager, resource)
                            users[
                                manager] = ADMIN_PERMISSIONS + VIEW_PERMISSIONS
            except GroupProfile.DoesNotExist:
                pass
        info = {'users': users, 'groups': groups}

        try:
            if hasattr(self, "layer"):
                info_layer = {
                    'users': get_users_with_perms(self.layer),
                    'groups': get_groups_with_perms(self.layer,
                                                    attach_perms=True)
                }
                for user in info_layer['users']:
                    if user in info['users']:
                        info['users'][user] = info['users'][user] + info_layer[
                            'users'][user]
                    else:
                        info['users'][user] = info_layer['users'][user]
                for group in info_layer['groups']:
                    if group in info['groups']:
                        info['groups'][group] = list(
                            dict.fromkeys(info['groups'][group] +
                                          info_layer['groups'][group]))
                    else:
                        info['groups'][group] = info_layer['groups'][group]
        except Exception:
            tb = traceback.format_exc()
            logger.debug(tb)
        return info
Esempio n. 5
0
 def get_object_list(self, request):
     try:
         user = request.user
         request_id = request.GET.get("request_id", None)
         user_id = request.GET.get("user_id", None)
         excluded = ['public', 'AnonymousUser']
         if request_id:
             req = Request.objects.get(id=request_id)
             if req.author == user:
                 excluded.append(user.username)
             if settings.DEBUG:
                 retval = get_groups_with_perms(req)
             else:
                 retval = get_groups_with_perms(req).exclude(
                     name__in=excluded)
         elif user_id:
             excluded.append(user.username)
             retval = user.groups.all().exclude(name__in=excluded)
         else:
             if settings.DEBUG:
                 excluded.append(user.username)
             retval = Group.objects.all()
         return retval
     except Exception as e:
         logger.info(e)
         return []
Esempio n. 6
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)
Esempio n. 7
0
 def get_object_list(self, request):
     try:
         user = request.user
         request_id = request.GET.get("request_id", None)
         user_id = request.GET.get("user_id", None)
         excluded = ['public', 'AnonymousUser']
         if request_id:
             req = Request.objects.get(id=request_id)
             if req.author == user:
                 excluded.append(user.username)
             if settings.DEBUG:
                 retval = get_groups_with_perms(req)
             else:
                 retval = get_groups_with_perms(req).exclude(name__in=excluded)
         elif user_id:
             excluded.append(user.username)
             retval = user.groups.all().exclude(name__in=excluded)
         else:
             if settings.DEBUG:
                 excluded.append(user.username)
             retval = Group.objects.all()
         return retval
     except Exception as e:
         logger.info(e)
         return []
Esempio n. 8
0
    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)
Esempio n. 9
0
    def test_empty(self):
        result = get_groups_with_perms(self.obj1)
        self.assertTrue(isinstance(result, QuerySet))
        self.assertFalse(bool(result))

        result = get_groups_with_perms(self.obj1, attach_perms=True)
        self.assertTrue(isinstance(result, dict))
        self.assertFalse(bool(result))
Esempio n. 10
0
    def test_empty(self):
        result = get_groups_with_perms(self.flatpage1)
        self.assertTrue(isinstance(result, QuerySet))
        self.assertFalse(bool(result))

        result = get_groups_with_perms(self.flatpage1, attach_perms=True)
        self.assertTrue(isinstance(result, dict))
        self.assertFalse(bool(result))
Esempio n. 11
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields['allotted_assignment_time'].label = 'Allotted assignment time (hours)'
        self.fields['allotted_assignment_time'].help_text = 'If a user abandons a Task, ' + \
            'this determines how long it takes until their assignment is deleted and ' + \
            'someone else can work on the Task.'
        self.fields['csv_file'].help_text = 'You can Drag-and-Drop a CSV file onto this ' + \
            'window, or use the "Choose File" button to browse for the file'
        self.fields['csv_file'].widget = CustomButtonFileWidget(attrs={
            'class': 'hidden',
            'data-parsley-errors-container': '#file-upload-error',
        })
        self.fields['custom_permissions'].label = 'Restrict access to specific Groups of Workers '
        self.fields['project'].label = 'Project'
        self.fields['name'].label = 'Batch Name'

        self.fields['active'].help_text = 'Workers can only access a Batch if both the Batch ' + \
            'itself and the associated Project are Active.'

        if self.instance._state.adding and 'project' in self.initial:
            # We are adding a new Batch where the associated Project has been specified.
            # Per Django convention, the project ID is specified in the URL, e.g.:
            #   /admin/turkle/batch/add/?project=94

            # NOTE: The fields that are initialized here should match the fields copied
            #       over by the batch.copy_project_permissions() function.

            project = Project.objects.get(id=int(self.initial['project']))
            self.fields['custom_permissions'].initial = project.custom_permissions
            self.fields['login_required'].initial = project.login_required

            # Pre-populate permissions using permissions from the associated Project
            initial_ids = [str(id)
                           for id in get_groups_with_perms(project).values_list('id', flat=True)]
        else:
            # Pre-populate permissions
            initial_ids = [str(id)
                           for id in get_groups_with_perms(self.instance).
                           values_list('id', flat=True)]
        self.fields['worker_permissions'].initial = initial_ids

        # csv_file field not required if changing existing Batch
        #
        # When changing a Batch, the BatchAdmin.get_fields()
        # function will cause the form to be rendered without
        # displaying an HTML form field for the csv_file field.  I was
        # running into strange behavior where Django would still try
        # to validate the csv_file form field, even though there was
        # no way for the user to provide a value for this field.  The
        # two lines below prevent this problem from occurring, by
        # making the csv_file field optional when changing
        # a Batch.
        if not self.instance._state.adding:
            self.fields['csv_file'].required = False
            self.fields['project'].widget = \
                ProjectNameReadOnlyWidget(self.instance.project)
Esempio n. 12
0
    def get_all_level_info(self):

        resource = self.get_self_resource()
        users = get_users_with_perms(resource)
        groups = get_groups_with_perms(resource, attach_perms=True)
        if groups:
            for group in groups:
                try:
                    group_profile = GroupProfile.objects.get(slug=group.name)
                    managers = group_profile.get_managers()
                    if managers:
                        for manager in managers:
                            if manager not in users and not manager.is_superuser:
                                for perm in ADMIN_PERMISSIONS:
                                    assign_perm(perm, manager, resource)
                                users[manager] = ADMIN_PERMISSIONS
                except GroupProfile.DoesNotExist:
                    pass
        info = {'users': users, 'groups': groups}

        # TODO very hugly here, but isn't huglier
        # to set layer permissions to resource base?
        if hasattr(self, "layer"):
            info_layer = {
                'users': get_users_with_perms(self.layer),
                'groups': get_groups_with_perms(self.layer, attach_perms=True)
            }

            for user in info_layer['users']:
                permissions = []
                if user in info['users']:
                    permissions = info['users'][user]
                else:
                    info['users'][user] = []

                for perm in info_layer['users'][user]:
                    if perm not in permissions:
                        permissions.append(perm)

            for group in info_layer['groups']:
                permissions = []
                if group in info['groups']:
                    permissions = info['groups'][group]
                else:
                    info['groups'][group] = []
                for perm in info_layer['groups'][group]:
                    if perm not in permissions:
                        permissions.append(perm)

        return info
Esempio n. 13
0
def add_task_to_groups(contest, task):
    for group in get_groups_with_perms(contest, attach_perms=True):
        GroupTaskDetails.objects.create(task=task,
                                        group=group,
                                        open=task.open,
                                        deadline=task.deadline,
                                        close=task.close)
Esempio n. 14
0
def alert_generator():
    """ Generates alerts for a given site """
    mails = []
    sms_numbers = []
    rules = Alert_Rule.objects.all()

    for rule in rules:
        site = rule.site
        site_groups = get_groups_with_perms(site)

        # Get datapoint and real value
        data_point, real_value = get_alert_check_value(rule)

        if data_point is not None and real_value is not None:
            if check_alert(rule, real_value):
                alert_obj = alert_factory(site, rule, data_point)

                # if alert_obj is created
                if alert_obj is not None:
                    content = get_alert_content(site, rule, data_point,
                                                real_value, alert_obj)
                    mails, sms_numbers = get_recipients_for_site(site)

                    # reporting
                    logging.debug("Alert triggered sending alerts out %s" %
                                  mails)
                    alert_obj.emailSent = send_mail("Alert Mail", mails,
                                                    content)
                    alert_obj.smsSent = send_sms(sms_numbers, content)
                    slack_msg = get_slack_alert_msg("Alert Triggered",
                                                    alert_obj)
                    alert_obj.slackSent = send_alert_slack(
                        site_groups, slack_msg)

                    alert_obj.save()
Esempio n. 15
0
    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)))))
            )
Esempio n. 16
0
    def augment_with_groups(self, dataset):
        dataset_object = Dataset.objects.get(dataset_id=dataset["id"])
        groups = get_groups_with_perms(dataset_object)
        serializer = GroupSerializer(groups, many=True)
        dataset["groups"] = serializer.data

        return dataset
Esempio n. 17
0
	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)
Esempio n. 18
0
    def get_queryset(self):
        """
        Builds a queryset of relevant users with permissions for this website, and annotates them by group name/role
        (owner, administrator, editor, or global administrator)
        """
        website = self.website
        website_group_names = list(
            get_groups_with_perms(website).values_list(
                "name", flat=True)) + [constants.GLOBAL_ADMIN]
        owner_user_id = website.owner.id if website.owner else None

        return (User.objects.filter(
            Q(id=owner_user_id)
            | Q(groups__name__in=website_group_names)).annotate(role=Case(
                When(id=owner_user_id, then=Value(constants.ROLE_OWNER)),
                default=Group.objects.filter(
                    user__id=OuterRef("id"),
                    name__in=website_group_names).annotate(role_name=Case(
                        *([
                            When(
                                name=permissions_group_name_for_role(
                                    role, website),
                                then=Value(role),
                            ) for role in constants.ROLE_GROUP_MAPPING
                        ]),
                        output_field=CharField(),
                    )).values("role_name")[:1],
                output_field=CharField(),
            )).order_by("name", "id").distinct())
Esempio n. 19
0
def view_dataset_permissions(request, dataset_id):
    try:
        dataset = HTSDataset.objects.get(id=dataset_id, deleted_date=None)
    except HTSDataset.DoesNotExist:
        raise Http404()

    if dataset.owner_id != request.user.id:
        raise Http404()

    available_perms = HTSDataset.view_dataset_permissions()

    all_groups = request.user.groups.all()
    groups_with_perms = get_groups_with_perms(dataset, True)

    group_perms = {}
    for gr in all_groups:
        matching_gr_perms = groups_with_perms.get(gr, [])
        group_perms[gr] = [(perm, perm in matching_gr_perms)
                           for perm in available_perms]

    response = render(
        request, 'dataset-permissions.html', {
            'dataset': dataset,
            'available_perms': available_perms,
            'group_perms': group_perms
        })

    return response
    def test_get_groups_with_perms_doesnt_spawn_extra_queries_for_more_groups_with_perms(self):
        Group.objects.create(name='managers')
        devs = Group.objects.create(name='devs')
        devs1 = Group.objects.create(name='devs1')
        devs2 = Group.objects.create(name='devs2')
        devs3 = Group.objects.create(name='devs3')
        devs4 = Group.objects.create(name='devs4')
        devs5 = Group.objects.create(name='devs5')
        assign_perm('add_project', self.group, self.project)
        assign_perm('change_project', self.group, self.project)
        for group in [devs, devs1, devs2, devs3, devs4, devs5]:
            assign_perm('add_project', group, self.project)
            assign_perm('change_project', group, self.project)

        with self.assertNumQueries(3):
            result = get_groups_with_perms(self.project, attach_perms=True)

        self.assertEqual(result,
                         {
                             self.group: ['add_project', 'change_project'],
                             devs: ['add_project', 'change_project'],
                             devs1: ['add_project', 'change_project'],
                             devs2: ['add_project', 'change_project'],
                             devs3: ['add_project', 'change_project'],
                             devs4: ['add_project', 'change_project'],
                             devs5: ['add_project', 'change_project'],
                         })
Esempio n. 21
0
def alert_generator():
    """ Generates alerts for a given site """
    mails = []
    sms_numbers = []
    rules = Alert_Rule.objects.all()

    for rule in rules:
        site = rule.site
        site_groups = get_groups_with_perms(site)

        # Get datapoint and real value
        data_point, real_value = get_alert_check_value(rule)


        if data_point is not None and real_value is not None:
            if check_alert(rule, real_value):
                alert_obj = alert_factory(site, rule, data_point)

                # if alert_obj is created
                if alert_obj is not None:
                    content = get_alert_content(site, rule, data_point, real_value, alert_obj)
                    mails, sms_numbers = get_recipients_for_site(site)

                    # reporting
                    alert_obj.emailSent = send_mail("Alert Mail", mails, content)
                    alert_obj.smsSent = send_sms(sms_numbers, content)
                    slack_msg = get_slack_alert_msg("Alert Triggered", alert_obj)
                    alert_obj.slackSent = send_alert_slack(site_groups, slack_msg)

                    alert_obj.save()
Esempio n. 22
0
 def render(self, context):
     user = context['user']
     item = context[self.item_name]
     type = item.__class__.__name__.lower()
     if user.has_perm('drama.change_' + type, item):
         subcontext = {}
         subcontext['approved'] = item.approved
         subcontext['type'] = type
         subcontext['item'] = item
         admin_perm = 'change_' + type
         if user.has_perm(admin_perm, item):
             subcontext['admin'] = True
             subcontext['users'] = item.group.user_set.all()
             subcontext['pending_users'] = item.group.pendinggroupmember_set.all()
             subcontext['admin_requests'] = item.get_admin_requests()
             groups = list(get_groups_with_perms(item).exclude(id=item.group.id))
             if type == 'show':
                 for society in item.societies.all():
                     groups = groups + [society.group]
                 for venue in Venue.objects.filter(performance__show=item).distinct():
                     groups = groups + [venue.group]
             subcontext['groups'] = groups
         if user.has_perm('drama.approve_' + type, item):
             subcontext['approve'] = True
         subcontext['staff'] = user.is_staff
         subcontext['csrf_token'] = context['csrf_token']
         return self.template.render(template.Context(subcontext))
     else:
         return ""
Esempio n. 23
0
def create_initial_site_statistics(apps, schema_editor):
    SiteStatistics = apps.get_model("core", "SiteStatistics")
    User = apps.get_model("auth", "User")
    ExtendedGroup = apps.get_model("core", "ExtendedGroup")
    WorkflowTool = apps.get_model("tool_manager", "WorkflowTool")
    VisualizationTool = apps.get_model("tool_manager", "VisualizationTool")
    UserProfile = apps.get_model("core", "UserProfile")
    DataSet = apps.get_model("core", "DataSet")

    SiteStatistics.objects.create(
        run_date=timezone.now(),
        datasets_uploaded=DataSet.objects.count(),
        datasets_shared=len([
            dataset for dataset in DataSet.objects.all()
            if get_groups_with_perms(dataset)
        ]),
        users_created=User.objects.count(),
        groups_created=ExtendedGroup.objects.exclude(
            manager_group=None).count(),
        unique_user_logins=User.objects.filter(
            last_login__lte=timezone.now()).count(),
        total_user_logins=sum(
            [u.login_count for u in UserProfile.objects.all()]),
        total_workflow_launches=WorkflowTool.objects.count(),
        total_visualization_launches=VisualizationTool.objects.count())
Esempio n. 24
0
 def to_representation(self, instance):
     representation = super().to_representation(instance)
     groups = []
     for group in get_groups_with_perms(instance):
         groups.append(GroupSerializer(group).data)
     representation['groups'] = groups
     return representation
Esempio n. 25
0
 def get_allowed_groups(self):
     allowed_groups = []
     groups = get_groups_with_perms(self, attach_perms=True)
     for group in groups.keys():
         if "group_view" in groups[group]:
             allowed_groups.append(group)
     return allowed_groups
Esempio n. 26
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields['template_file_upload'].widget = CustomButtonFileWidget()

        # This hidden form field is updated by JavaScript code in the
        # customized admin template file:
        #   turkle/templates/admin/turkle/project/change_form.html
        self.fields['filename'].widget = HiddenInput()

        self.fields['assignments_per_task'].label = 'Assignments per Task'
        self.fields['assignments_per_task'].help_text = 'This parameter sets the default ' + \
            'number of Assignments per Task for new Batches of Tasks.  Changing this ' + \
            'parameter DOES NOT change the number of Assignments per Task for already ' + \
            'published batches of Tasks.'
        self.fields['custom_permissions'].label = 'Restrict access to specific Groups of Workers '
        self.fields['html_template'].label = 'HTML template text'
        limit = str(get_turkle_template_limit())
        self.fields['html_template'].help_text = 'You can edit the template text directly, ' + \
            'Drag-and-Drop a template file onto this window, ' + \
            'or use the "Choose File" button below. Maximum size is ' + limit + ' KB.'
        byte_limit = str(get_turkle_template_limit(True))
        self.fields['html_template'].widget.attrs['data-parsley-maxlength'] = byte_limit
        self.fields['html_template'].widget.attrs['data-parsley-group'] = 'html_template'

        initial_ids = [str(id)
                       for id in get_groups_with_perms(self.instance).values_list('id', flat=True)]
        self.fields['worker_permissions'].initial = initial_ids
Esempio n. 27
0
 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
Esempio n. 28
0
def ajax_get_tag_groups(request, tag_type):
    if not request.user.is_authenticated:
        return JsonResponse({}, status=401)

    tag_cls = DrugTag if tag_type == 'drugs' else CellLineTag
    try:
        tag_ids = request.GET.getlist('tagId')
    except KeyError:
        return JsonResponse({'error': 'Malformed request'}, status=400)

    tags = tag_cls.objects.filter(owner=request.user, pk__in=tag_ids)
    if len(tags) < len(tag_ids):
        return JsonResponse({'error': 'Some tags are not owned by you or '
                                      'have not been found'}, status=400)

    user_groups = request.user.groups.all()
    tag_groups = {tag.id: get_groups_with_perms(tag) for tag in tags}
    # Invert tag_groups to get group_tags
    group_tags = {g.id: set() for g in user_groups}
    for tag_id, groups in tag_groups.items():
        for group in groups:
            group_tags[group.id].add(tag_id)

    return JsonResponse({'groups': [{
        'groupId': g.id,
        'groupName': g.name,
        'tagIds': list(group_tags[g.id])
    } for g in user_groups]})
Esempio n. 29
0
    def save_model(self, request, obj, form, change):
        """
        For reasons that are beyond me, saving the object from the admin panel didn't save the User object. This
        overrides save to get the user from request, to which the Admin models have access.

        Use assign_perm from django-admin to give the creator's group permissions to the object instance. If the creator
        does not have only one group, presumably the person is an admin. Use the messages framework to flash a WARNING
        if when this happens to alert the admin to set the permissions manually.

        In conjunction with the get_queryset() override above, the result is that viewing the AppointmentAdmin page
        shows only instances of Appointment that one (or one's group) owns.
        """
        obj.created_by = request.user
        super(AppointmentAdmin, self).save_model(request, obj, form, change)
        # With the object persisted, permissions can now be granted.
        creator = obj.created_by
        if creator.groups.count() != 1:
            if not get_groups_with_perms(obj):
                messages.add_message(
                    request, messages.WARNING,
                    'Remember: until you you change this APPOINTMENT\'S '
                    'object permissions, no organization can see it.')
        else:
            group = creator.groups.first()
            assign_perm('change_appointment', group, obj)
            assign_perm('view_appointment', group, obj)
            assign_perm('delete_appointment', group, obj)
Esempio n. 30
0
    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 create_initial_site_statistics(apps, schema_editor):
    SiteStatistics = apps.get_model("core", "SiteStatistics")
    User = apps.get_model("auth", "User")
    ExtendedGroup = apps.get_model("core", "ExtendedGroup")
    WorkflowTool = apps.get_model("tool_manager", "WorkflowTool")
    VisualizationTool = apps.get_model("tool_manager", "VisualizationTool")
    UserProfile = apps.get_model("core", "UserProfile")
    DataSet = apps.get_model("core", "DataSet")

    SiteStatistics.objects.create(
        run_date=timezone.now(),
        datasets_uploaded=DataSet.objects.count(),
        datasets_shared=len(
             [dataset for dataset in DataSet.objects.all() if
              get_groups_with_perms(dataset)]
        ),
        users_created=User.objects.count(),
        groups_created=ExtendedGroup.objects.exclude(
            manager_group=None
        ).count(),
        unique_user_logins=User.objects.filter(
            last_login__lte=timezone.now()
        ).count(),
        total_user_logins=sum([u.login_count for u in
                              UserProfile.objects.all()]),
        total_workflow_launches=WorkflowTool.objects.count(),
        total_visualization_launches=VisualizationTool.objects.count()
    )
Esempio n. 32
0
    def test_get_groups_with_perms_doesnt_spawn_extra_queries_for_more_groups_with_perms(
            self):
        Group.objects.create(name='managers')
        devs = Group.objects.create(name='devs')
        devs1 = Group.objects.create(name='devs1')
        devs2 = Group.objects.create(name='devs2')
        devs3 = Group.objects.create(name='devs3')
        devs4 = Group.objects.create(name='devs4')
        devs5 = Group.objects.create(name='devs5')
        assign_perm('add_project', self.group, self.project)
        assign_perm('change_project', self.group, self.project)
        for group in [devs, devs1, devs2, devs3, devs4, devs5]:
            assign_perm('add_project', group, self.project)
            assign_perm('change_project', group, self.project)

        with self.assertNumQueries(3):
            result = get_groups_with_perms(self.project, attach_perms=True)

        self.assertEqual(
            result, {
                self.group: ['add_project', 'change_project'],
                devs: ['add_project', 'change_project'],
                devs1: ['add_project', 'change_project'],
                devs2: ['add_project', 'change_project'],
                devs3: ['add_project', 'change_project'],
                devs4: ['add_project', 'change_project'],
                devs5: ['add_project', 'change_project'],
            })
Esempio n. 33
0
def get_perms(request, biz_cc_id):
    template_id = request.GET.get('template_id')
    try:
        template = TaskTemplate.objects.get(pk=template_id,
                                            business__cc_id=biz_cc_id)
    except TaskTemplate.DoesNotExist:
        return HttpResponseForbidden()
    all_perms = [
        CREATE_TASK_PERM_NAME, FILL_PARAMS_PERM_NAME, EXECUTE_TASK_PERM_NAME
    ]
    data = {('%s_groups' % perm): [] for perm in all_perms}
    # 获取有权限的分组列表
    groups = get_groups_with_perms(template, attach_perms=True)
    for group, perm_list in groups.items():
        for perm in perm_list:
            data['%s_groups' % perm].append(
                {"show_name": group.name.split("\x00")[-1]})
    # 获取有权限的人员列表(单独按人员角色授权,而不是按分组授权)
    users = get_users_with_perms(template,
                                 attach_perms=True,
                                 with_group_users=False)
    for user, perm_list in users.items():
        for perm in perm_list:
            data['%s_groups' % perm].append({"show_name": user.username})
    ctx = {'result': True, 'data': data}
    return JsonResponse(ctx)
Esempio n. 34
0
def get_perms(request):
    """
    @summary: 暴露给业务的接口,业务人员获取自己业务下的权限
    @param request:
    @return:
    """
    template_id = request.GET.get('template_id')
    biz_cc_id = str(request.GET.get('biz_cc_id'))

    try:
        CommonTemplate.objects.get(pk=template_id, is_deleted=False)
    except CommonTemplate.DoesNotExist:
        return HttpResponseForbidden()
    template_perm, _ = CommonTmplPerm.objects.get_or_create(
        common_template_id=template_id, biz_cc_id=biz_cc_id)
    data = {perm: [] for perm in PermNm.PERM_LIST}
    common_perm_list = ['common_%s' % perm for perm in PermNm.PERM_LIST]
    index = len('common_')
    # 获取有权限的分组列表
    groups = get_groups_with_perms(template_perm, attach_perms=True)
    for group, perm_list in groups.items():
        for perm in perm_list:
            if perm in common_perm_list:
                data[perm[index:]].append(
                    {"show_name": group.name.split("\x00")[-1]})
    # 获取有权限的人员列表(单独按人员角色授权,而不是按分组授权)
    users = get_users_with_perms(template_perm,
                                 attach_perms=True,
                                 with_group_users=False)
    for user, perm_list in users.items():
        for perm in perm_list:
            if perm in common_perm_list:
                data[perm[index:]].append({"show_name": user.username})
    ctx = {'result': True, 'data': data, 'message': 'success'}
    return JsonResponse(ctx)
Esempio n. 35
0
def fetch_task(request, id):
    contest = Contest.objects.get(pk=id)
    if not request.user.has_perm('manage_contest', contest):
        permission_denied_message(request)
    elif request.method == 'POST':
        form = TaskFetchForm(request.POST)
        if form.is_valid():
            parent_task = form.cleaned_data['task']
            fetched_task = deepcopy(parent_task)
            fetched_task.pk = None
            fetched_task.contest = contest
            fetched_task.parent = parent_task
            fetched_task.open = form.cleaned_data['open']
            fetched_task.deadline = form.cleaned_data['deadline']
            fetched_task.close = form.cleaned_data['close']
            fetched_task.save()
            messages.add_message(request, messages.SUCCESS, "New task has been added to contest %s."
                                 % contest.name)
            # add tasks to groups
            for group in get_groups_with_perms(contest, attach_perms=True):
                GroupTaskDetails.objects.create(task=fetched_task, group=group,
                                                open=fetched_task.open, deadline=fetched_task.deadline,
                                                close=fetched_task.close)

    return HttpResponseRedirect(reverse('contest_details',
                                        args=[id, 'tasks']))
Esempio n. 36
0
	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)
Esempio n. 37
0
    def save(self, commit=True):
        instance = super().save(commit=commit)
        if commit:
            for field in settings.EXTRA_FIELDS:
                if self.cleaned_data.get(field['name']) is not None:
                    TargetExtra.objects.update_or_create(
                        target=instance,
                        key=field['name'],
                        defaults={'value': self.cleaned_data[field['name']]})
            # Save groups for this target
            for group in self.cleaned_data['groups']:
                assign_perm('tom_targets.view_target', group, instance)
                assign_perm('tom_targets.change_target', group, instance)
                assign_perm('tom_targets.delete_target', group, instance)
            for group in get_groups_with_perms(instance):
                if group not in self.cleaned_data['groups']:
                    remove_perm('tom_targets.view_target', group, instance)
                    remove_perm('tom_targets.change_target', group, instance)
                    remove_perm('tom_targets.delete_target', group, instance)

            # Save science tags for this target
            for tag in self.cleaned_data['sciencetags']:
                TargetTags.objects.update_or_create(target=instance, tag=tag)

        return instance
Esempio n. 38
0
def add_task_to_groups(contest, task):
    for group in get_groups_with_perms(contest, attach_perms=True):
        GroupTaskDetails.objects.create(task=task,
                                        group=group,
                                        open=task.open,
                                        deadline=task.deadline,
                                        close=task.close)
Esempio n. 39
0
    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}
Esempio n. 40
0
    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}
Esempio n. 41
0
    def get_context_data(self, **kwargs):

        context = ContextMixin.get_context_data(self, **kwargs)

        if self.request.method == "POST":
            if self.request.POST.get("group"):
                context["group_form"] = self.get_form()
            else:
                context["user_form"] = self.get_form()

        context.setdefault("group_form", SecretGroupPermissionsForm())
        context.setdefault("user_form", SecretUserPermissionsForm())

        pk = context["pk"] = self.kwargs["pk"]
        context["tab"] = "permissions"
        context["object"] = Secret.objects.get(pk=self.kwargs["pk"])

        secret = Secret.objects.get(pk=pk)

        users = get_users_with_perms(
            secret,
            attach_perms=True,
            with_superusers=False,
            with_group_users=False,
            only_with_perms_in=[
                EDIT_SECRET_PERMISSION, VIEW_SECRET_PERMISSION
            ],
        )

        def select_perm(perms):
            return "change_secret" if "change_secret" in perms else "view_secret"

        context["users"] = [{
            "user":
            user,
            "form":
            SecretPermissionsForm(
                update_permission=True,
                initial={
                    "user": user,
                    "permission": select_perm(perms)
                },
            ),
        } for user, perms in users.items()]
        groups = get_groups_with_perms(secret, attach_perms=True)

        context["groups"] = [{
            "group":
            group,
            "form":
            SecretPermissionsForm(
                update_permission=True,
                initial={
                    "group": group,
                    "permission": select_perm(perms)
                },
            ),
        } for group, perms in groups.items()]

        return context
Esempio n. 42
0
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("[]")
Esempio n. 43
0
 def get_manager_group( self ):
     # ownership is determined by "add" permission
     group_permissions = get_groups_with_perms( self, attach_perms=True )
     
     for group, permission in group_permissions.iteritems():
         if "add_%s" % self._meta.verbose_name in permission:
             return group.extendedgroup
Esempio n. 44
0
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("[]")
Esempio n. 45
0
def get_perms(request, biz_cc_id):
    template_id = request.GET.get('template_id')
    try:
        template = TaskTemplate.objects.get(pk=template_id,
                                            business__cc_id=biz_cc_id,
                                            is_deleted=False)
    except TaskTemplate.DoesNotExist:
        return HttpResponseForbidden()
    data = {perm: [] for perm in PermNm.PERM_LIST}
    # 获取有权限的分组列表
    groups = get_groups_with_perms(template, attach_perms=True)
    for group, perm_list in groups.items():
        for perm in perm_list:
            if perm in PermNm.PERM_LIST:
                data[perm].append({"show_name": group.name.split("\x00")[-1]})
    # 获取有权限的人员列表(单独按人员角色授权,而不是按分组授权)
    users = get_users_with_perms(template,
                                 attach_perms=True,
                                 with_group_users=False)
    for user, perm_list in users.items():
        for perm in perm_list:
            if perm in PermNm.PERM_LIST:
                data[perm].append({"show_name": user.username})
    ctx = {'result': True, 'data': data, 'message': 'success'}
    return JsonResponse(ctx)
Esempio n. 46
0
    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
Esempio n. 47
0
    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))
Esempio n. 48
0
    def get_all_level_info(self):

        resource = self.get_self_resource()
        users = get_users_with_perms(resource)
        groups = get_groups_with_perms(resource,
                                       attach_perms=True)
        if groups:
            for group in groups:
                try:
                    group_profile = GroupProfile.objects.get(slug=group.name)
                    managers = group_profile.get_managers()
                    if managers:
                        for manager in managers:
                            if manager not in users and not manager.is_superuser:
                                for perm in ADMIN_PERMISSIONS:
                                    assign_perm(perm, manager, resource)
                                users[manager] = ADMIN_PERMISSIONS
                except GroupProfile.DoesNotExist:
                    pass
        info = {
            'users': users,
            'groups': groups}

        # TODO very hugly here, but isn't huglier
        # to set layer permissions to resource base?
        if hasattr(self, "layer"):
            info_layer = {
                'users': get_users_with_perms(
                    self.layer),
                'groups': get_groups_with_perms(
                    self.layer,
                    attach_perms=True)}

            for user in info_layer['users']:
                if user in info['users']:
                    info['users'][user] = info['users'][user] + info_layer['users'][user]
                else:
                    info['users'][user] = info_layer['users'][user]

            for group in info_layer['groups']:
                if group in info['groups']:
                    info['groups'][group] = info['groups'][group] + info_layer['groups'][group]
                else:
                    info['groups'][group] = info_layer['groups'][group]

        return info
Esempio n. 49
0
    def test_mixed_attach_perms(self):
        self.test_mixed()

        result = get_groups_with_perms(self.flatpage1, attach_perms=True)
        expected = {
            self.group1: ["change_flatpage"],
            self.group2: ["change_flatpage", "delete_flatpage"],
        }
        self.assertEqual(result, expected)
Esempio n. 50
0
	def has_perms(self):
		group_perms = get_groups_with_perms(self, attach_perms=True)
		content_type = ContentType.objects.get_for_model(self)
		for perms in group_perms.values():
			for perm in perms:
				perm = "{app}.{perm}".format(app=content_type.app_label, perm=perm)
				if perm != self.add_permission_name:
					return True
		return False
Esempio n. 51
0
    def get_group_ids(self, changeonly=False, readonly=False):
        groups = get_groups_with_perms(self)

        ids = []

        for group in groups:
            ids.append(group.id)

        return ids
 def test_get_groups_with_perms(self):
     Group.objects.create(name="managers")
     devs = Group.objects.create(name="devs")
     assign_perm("add_project", self.group, self.project)
     assign_perm("change_project", self.group, self.project)
     assign_perm("change_project", devs, self.project)
     self.assertEqual(
         get_groups_with_perms(self.project, attach_perms=True),
         {self.group: ["add_project", "change_project"], devs: ["change_project"]},
     )
Esempio n. 53
0
 def get_privacy_string(self):
     shared_with = get_groups_with_perms(self)
     retval = "Nothing"
     if self.private == True and len(shared_with) == 1:
         retval = "This request is private"
     elif self.private == True and len(shared_with) > 1:#TODO DOUBLE CHECK ME
         retval = "This request is private but shared with others"
     else:
         retval = "This request is public"
     return retval
Esempio n. 54
0
def page_permissions(request, id):
    obj = get_object_or_404(Page, id=id)

    GroupsForm = get_groups_form(Group.objects.all(), initial=list(get_groups_with_perms(obj)))
    groups_form = GroupsForm()


    return render(request, 'professionals_pages/administration/permissions.html', {
        'page': obj,
        'groups_form': groups_form,
    })
Esempio n. 55
0
    def test_mixed(self):
        assign("change_flatpage", self.group1, self.flatpage1)
        assign("change_flatpage", self.group1, self.flatpage2)
        assign("change_user", self.group1, self.user3)
        assign("change_flatpage", self.group2, self.flatpage2)
        assign("change_flatpage", self.group2, self.flatpage1)
        assign("delete_flatpage", self.group2, self.flatpage1)
        assign("change_user", self.group3, self.user1)

        result = get_groups_with_perms(self.flatpage1)
        self.assertEqual(set(result), set([self.group1, self.group2]))
    def test_mixed(self):
        assign_perm("change_contenttype", self.group1, self.obj1)
        assign_perm("change_contenttype", self.group1, self.obj2)
        assign_perm("change_%s" % user_module_name, self.group1, self.user3)
        assign_perm("change_contenttype", self.group2, self.obj2)
        assign_perm("change_contenttype", self.group2, self.obj1)
        assign_perm("delete_contenttype", self.group2, self.obj1)
        assign_perm("change_%s" % user_module_name, self.group3, self.user1)

        result = get_groups_with_perms(self.obj1)
        self.assertEqual(set(result), set([self.group1, self.group2]))
Esempio n. 57
0
 def test_get_groups_with_perms(self):
     Group.objects.create(name='managers')
     devs = Group.objects.create(name='devs')
     assign('add_project', self.group, self.project)
     assign('change_project', self.group, self.project)
     assign('change_project', devs, self.project)
     self.assertEqual(get_groups_with_perms(self.project, attach_perms=True),
         {
             self.group: ['add_project', 'change_project'],
             devs: ['change_project'],
         })