Пример #1
0
def remove_perm(perm, user_or_group=None, obj=None):
    """
    Removes permission from user/group and object pair.

    :param perm: proper permission for given ``obj``, as string (in format:
      ``app_label.codename`` or ``codename``). If ``obj`` is not given, must
      be in format ``app_label.codename``.

    :param user_or_group: instance of ``User``, ``AnonymousUser`` or ``Group``;
      passing any other object would raise
      ``guardian.exceptions.NotUserNorGroup`` exception

    :param obj: persisted Django's ``Model`` instance or QuerySet of Django
      ``Model`` instances or ``None`` if assigning global permission.
      Default is ``None``.

    """
    db = user_or_group._state.db

    user, group = get_identity(user_or_group)
    if obj is None:
        try:
            app_label, codename = perm.split('.', 1)
        except ValueError:
            raise ValueError(
                "For global permissions, first argument must be in"
                " format: 'app_label.codename' (is %r)" % perm)
        perm = Permission.objects.using(db).get(
            content_type__app_label=app_label, codename=codename)
        if user:
            user.user_permissions.remove(perm)
            return
        elif group:
            group.permissions.remove(perm)
            return

    if not isinstance(perm, Permission):
        perm = perm.split('.')[-1]

    if isinstance(obj, QuerySet):
        if user:
            model = get_user_obj_perms_model(obj.model, user)
            return model.objects.db_manager(db).bulk_remove_perm(
                perm, user, obj)
        if group:
            model = get_group_obj_perms_model(obj.model, group)
            return model.objects.db_manager(db).bulk_remove_perm(
                perm, group, obj)

    if user:
        model = get_user_obj_perms_model(obj, user)
        return model.objects.db_manager(db).remove_perm(perm, user, obj)

    if group:
        model = get_group_obj_perms_model(obj, group)
        return model.objects.db_manager(db).remove_perm(perm, group, obj)
Пример #2
0
def remove_perm(perm, user_or_group=None, obj=None):
    """
    Removes permission from user/group and object pair.

    :param perm: proper permission for given ``obj``, as string (in format:
      ``app_label.codename`` or ``codename``). If ``obj`` is not given, must
      be in format ``app_label.codename``.

    :param user_or_group: instance of ``User``, ``AnonymousUser`` or ``Group``;
      passing any other object would raise
      ``guardian.exceptions.NotUserNorGroup`` exception

    :param obj: persisted Django's ``Model`` instance or QuerySet of Django
      ``Model`` instances or ``None`` if assigning global permission.
      Default is ``None``.

    """
    user, group = get_identity(user_or_group)
    if obj is None:
        try:
            app_label, codename = perm.split('.', 1)
        except ValueError:
            raise ValueError("For global permissions, first argument must be in"
                             " format: 'app_label.codename' (is %r)" % perm)
        perm = Permission.objects.get(content_type__app_label=app_label,
                                      codename=codename)
        if user:
            user.user_permissions.remove(perm)
            return
        elif group:
            group.permissions.remove(perm)
            return

    if not isinstance(perm, Permission):
        perm = perm.split('.')[-1]

    if isinstance(obj, QuerySet):
        if user:
            model = get_user_obj_perms_model(obj.model)
            return model.objects.bulk_remove_perm(perm, user, obj)
        if group:
            model = get_group_obj_perms_model(obj.model)
            return model.objects.bulk_remove_perm(perm, group, obj)

    if user:
        model = get_user_obj_perms_model(obj)
        return model.objects.remove_perm(perm, user, obj)

    if group:
        model = get_group_obj_perms_model(obj)
        return model.objects.remove_perm(perm, group, obj)
Пример #3
0
def get_groups_with_perms(obj, attach_perms=False):
    """Return queryset of all ``Group`` objects with *any* object permissions for the given ``obj``."""
    ctype = get_content_type(obj)
    group_model = get_group_obj_perms_model(obj)

    if not attach_perms:
        # It's much easier without attached perms so we do it first if that is the case
        group_rel_name = group_model.group.field.related_query_name()
        if group_model.objects.is_generic():
            group_filters = {
                '%s__content_type' % group_rel_name: ctype,
                '%s__object_pk' % group_rel_name: obj.pk,
            }
        else:
            group_filters = {'%s__content_object' % group_rel_name: obj}
        return Group.objects.filter(**group_filters).distinct()
    else:
        group_perms_mapping = defaultdict(list)
        groups_with_perms = get_groups_with_perms(obj)
        queryset = group_model.objects.filter(group__in=groups_with_perms).prefetch_related('group', 'permission')
        if group_model is GroupObjectPermission:
            queryset = queryset.filter(object_pk=obj.pk, content_type=ctype)
        else:
            queryset = queryset.filter(content_object_id=obj.pk)

        for group_perm in queryset:
            group_perms_mapping[group_perm.group].append(group_perm.permission.codename)
        return dict(group_perms_mapping)
Пример #4
0
def get_groups_with_perms(obj, attach_perms=False):
    """
    Returns queryset of all ``Group`` objects with *any* object permissions for
    the given ``obj``.

    :param obj: persisted Django's ``Model`` instance

    :param attach_perms: Default: ``False``. If set to ``True`` result would be
      dictionary of ``Group`` instances with permissions' codenames list as
      values. This would fetch groups eagerly!

    Example::

        >>> from django.contrib.flatpages.models import FlatPage
        >>> from guardian.shortcuts import assign_perm, get_groups_with_perms
        >>> from guardian.models import Group
        >>>
        >>> page = FlatPage.objects.create(title='Some page', path='/some/page/')
        >>> admins = Group.objects.create(name='Admins')
        >>> assign_perm('change_flatpage', admins, page)
        >>>
        >>> get_groups_with_perms(page)
        [<Group: admins>]
        >>>
        >>> get_groups_with_perms(page, attach_perms=True)
        {<Group: admins>: [u'change_flatpage']}

    """
    ctype = get_content_type(obj)
    group_model = get_group_obj_perms_model(obj)

    if not attach_perms:
        # It's much easier without attached perms so we do it first if that is the case
        group_rel_name = group_model.group.field.related_query_name()
        if group_model.objects.is_generic():
            group_filters = {
                '%s__content_type' % group_rel_name: ctype,
                '%s__object_pk' % group_rel_name: obj.pk,
            }
        else:
            group_filters = {'%s__content_object' % group_rel_name: obj}
        return Group.objects.filter(**group_filters).distinct()
    else:
        group_perms_mapping = defaultdict(list)
        groups_with_perms = get_groups_with_perms(obj)
        qs = group_model.objects.filter(
            group__in=groups_with_perms).prefetch_related(
                'group', 'permission')
        if group_model is GroupObjectPermission:
            qs = qs.filter(object_pk=obj.pk, content_type=ctype)
        else:
            qs = qs.filter(content_object_id=obj.pk)

        for group_perm in qs:
            group_perms_mapping[group_perm.group].append(
                group_perm.permission.codename)
        return dict(group_perms_mapping)
Пример #5
0
def get_user_group_perms(user_or_group, obj):
    """Get permissins for user groups.

    Based on guardian.core.ObjectPermissionChecker.

    """
    user, group = get_identity(user_or_group)

    if user and not user.is_active:
        return [], []
    user_model = get_user_model()
    ctype = ContentType.objects.get_for_model(obj)

    group_model = get_group_obj_perms_model(obj)
    group_rel_name = group_model.permission.field.related_query_name()
    if user:
        user_rel_name = user_model.groups.field.related_query_name()
        group_filters = {user_rel_name: user}
    else:
        group_filters = {'pk': group.pk}
    if group_model.objects.is_generic():
        group_filters.update({
            '{}__content_type'.format(group_rel_name): ctype,
            '{}__object_pk'.format(group_rel_name): obj.pk,
        })
    else:
        group_filters['{}__content_object'.format(group_rel_name)] = obj

    user_perms, group_perms = [], []

    if user:
        perms_qs = Permission.objects.filter(content_type=ctype)
        if user.is_superuser:
            user_perms = list(chain(perms_qs.values_list("codename", flat=True)))
        else:
            model = get_user_obj_perms_model(obj)
            related_name = model.permission.field.related_query_name()
            user_filters = {'{}__user'.format(related_name): user}
            if model.objects.is_generic():
                user_filters.update({
                    '{}__content_type'.format(related_name): ctype,
                    '{}__object_pk'.format(related_name): obj.pk,
                })
            else:
                user_filters['{}__content_object'.format(related_name)] = obj

            user_perms_qs = perms_qs.filter(**user_filters)
            user_perms = list(chain(user_perms_qs.values_list("codename", flat=True)))

    group_perms_qs = Group.objects.filter(**group_filters)
    group_perms = list(chain(group_perms_qs.order_by("pk").values_list(
        "pk", "name", "{}__permission__codename".format(group_rel_name))))

    group_perms = _group_groups(group_perms)

    return user_perms, group_perms
Пример #6
0
def get_user_group_perms(user_or_group, obj):
    """Get permissins for user groups.

    Based on guardian.core.ObjectPermissionChecker.

    """
    user, group = get_identity(user_or_group)

    if user and not user.is_active:
        return [], []
    user_model = get_user_model()
    ctype = ContentType.objects.get_for_model(obj)

    group_model = get_group_obj_perms_model(obj)
    group_rel_name = group_model.permission.field.related_query_name()  # pylint: disable=no-member
    if user:
        user_rel_name = user_model.groups.field.related_query_name()  # pylint: disable=no-member
        group_filters = {user_rel_name: user}
    else:
        group_filters = {'pk': group.pk}
    if group_model.objects.is_generic():
        group_filters.update({
            '{}__content_type'.format(group_rel_name): ctype,
            '{}__object_pk'.format(group_rel_name): obj.pk,
        })
    else:
        group_filters['{}__content_object'.format(group_rel_name)] = obj

    user_perms, group_perms = [], []

    if user:
        perms_qs = Permission.objects.filter(content_type=ctype)
        if user.is_superuser:
            user_perms = list(chain(perms_qs.values_list("codename", flat=True)))
        else:
            model = get_user_obj_perms_model(obj)
            related_name = model.permission.field.related_query_name()  # pylint: disable=no-member
            user_filters = {'{}__user'.format(related_name): user}
            if model.objects.is_generic():
                user_filters.update({
                    '{}__content_type'.format(related_name): ctype,
                    '{}__object_pk'.format(related_name): obj.pk,
                })
            else:
                user_filters['{}__content_object'.format(related_name)] = obj

            user_perms_qs = perms_qs.filter(**user_filters)
            user_perms = list(chain(user_perms_qs.values_list("codename", flat=True)))

    group_perms_qs = Group.objects.filter(**group_filters)
    group_perms = list(chain(group_perms_qs.order_by("pk").values_list(
        "pk", "name", "{}__permission__codename".format(group_rel_name))))

    group_perms = _group_groups(group_perms)

    return user_perms, group_perms
Пример #7
0
def get_user_group_perms(user_or_group, obj):
    user, group = get_identity(user_or_group)

    if user and not user.is_active:
        return [], []
    User = get_user_model()
    ctype = ContentType.objects.get_for_model(obj)

    group_model = get_group_obj_perms_model(obj)
    group_rel_name = group_model.permission.field.related_query_name()
    if user:
        fieldname = '%s__group__%s' % (
            group_rel_name,
            User.groups.field.related_query_name(),
        )
        group_filters = {fieldname: user}
    else:
        group_filters = {'%s__group' % group_rel_name: group}
    if group_model.objects.is_generic():
        group_filters.update({
            '%s__content_type' % group_rel_name: ctype,
            '%s__object_pk' % group_rel_name: obj.pk,
        })
    else:
        group_filters['%s__content_object' % group_rel_name] = obj

    user_perms = []
    group_perms = []

    if user and user.is_superuser:
        user_perms = list(chain(*Permission.objects
                                .filter(content_type=ctype)
                                .values_list("codename")))
    elif user:
        model = get_user_obj_perms_model(obj)
        related_name = model.permission.field.related_query_name()
        user_filters = {'%s__user' % related_name: user}
        if model.objects.is_generic():
            user_filters.update({
                '%s__content_type' % related_name: ctype,
                '%s__object_pk' % related_name: obj.pk,
            })
        else:
            user_filters['%s__content_object' % related_name] = obj
        perms_qs = Permission.objects.filter(content_type=ctype)
        user_perms_qs = perms_qs.filter(**user_filters)
        user_perms = user_perms_qs.values_list("codename", flat=True)
        group_perms_qs = perms_qs.filter(**group_filters)
        group_perms = group_perms_qs.values_list("codename", flat=True)
    else:
        user_perms = list(set(chain(*Permission.objects
                                    .filter(content_type=ctype)
                                    .filter(**group_filters)
                                    .values_list("codename"))))

    return user_perms, group_perms
Пример #8
0
def get_groups_with_perms(obj, attach_perms=False):
    """
    Returns queryset of all ``Group`` objects with *any* object permissions for
    the given ``obj``.

    :param obj: persisted Django's ``Model`` instance

    :param attach_perms: Default: ``False``. If set to ``True`` result would be
      dictionary of ``Group`` instances with permissions' codenames list as
      values. This would fetch groups eagerly!

    Example::

        >>> from django.contrib.flatpages.models import FlatPage
        >>> from guardian.shortcuts import assign_perm, get_groups_with_perms
        >>> from guardian.models import Group
        >>>
        >>> page = FlatPage.objects.create(title='Some page', path='/some/page/')
        >>> admins = Group.objects.create(name='Admins')
        >>> assign_perm('change_flatpage', admins, page)
        >>>
        >>> get_groups_with_perms(page)
        [<Group: admins>]
        >>>
        >>> get_groups_with_perms(page, attach_perms=True)
        {<Group: admins>: [u'change_flatpage']}

    """
    ctype = get_content_type(obj)
    group_model = get_group_obj_perms_model(obj)

    if not attach_perms:
        # It's much easier without attached perms so we do it first if that is the case
        group_rel_name = group_model.group.field.related_query_name()
        if group_model.objects.is_generic():
            group_filters = {
                '%s__content_type' % group_rel_name: ctype,
                '%s__object_pk' % group_rel_name: obj.pk,
            }
        else:
            group_filters = {'%s__content_object' % group_rel_name: obj}
        return Group.objects.filter(**group_filters).distinct()
    else:
        group_perms_mapping = defaultdict(list)
        groups_with_perms = get_groups_with_perms(obj)
        qs = group_model.objects.filter(group__in=groups_with_perms).prefetch_related('group', 'permission')
        if group_model is GroupObjectPermission:
            qs = qs.filter(object_pk=obj.pk, content_type=ctype)
        else:
            qs = qs.filter(content_object_id=obj.pk)

        for group_perm in qs:
            group_perms_mapping[group_perm.group].append(group_perm.permission.codename)
        return dict(group_perms_mapping)
Пример #9
0
    def __get_raw_perms(self, obj):
        """
        Get all perms for ``obj`` (and descendents if exists), without filter by content_type.
        """
        User = get_user_model()
        ctype = ContentType.objects.get_for_model(obj)
        group_model = get_group_obj_perms_model(obj)
        group_rel_name = group_model.permission.field.related_query_name()
        if self.user:
            fieldname = '%s__group__%s' % (
                group_rel_name,
                User.groups.field.related_query_name(),
            )
            group_filters = {fieldname: self.user}
        else:
            group_filters = {'%s__group' % group_rel_name: self.group}
        if group_model.objects.is_generic():
            group_filters.update({
                '%s__content_type' % group_rel_name: ctype,
                '%s__object_pk' % group_rel_name: obj.pk,
            })
        else:
            group_filters['%s__content_object' % group_rel_name] = obj

        if self.user and not self.user.is_active:
            return []
        elif self.user and self.user.is_superuser:
            perms = set(Permission.objects.all())
        elif self.user:
            model = get_user_obj_perms_model(obj)
            related_name = model.permission.field.related_query_name()
            user_filters = {'%s__user' % related_name: self.user}
            if model.objects.is_generic():
                user_filters.update({
                    '%s__content_type' % related_name: ctype,
                    '%s__object_pk' % related_name: obj.pk,
                })
            else:
                user_filters['%s__content_object' % related_name] = obj

            perms_qs = Permission.objects
            # Query user and group permissions separately and then combine
            # the results to avoid a slow query
            user_perms_qs = perms_qs.filter(**user_filters)
            user_perms = user_perms_qs
            group_perms_qs = perms_qs.filter(**group_filters)
            group_perms = group_perms_qs
            perms = set(chain(user_perms, group_perms))
        else:
            #for group
            perms = set(Permission.objects.filter(**group_filters))
        return perms
def get_groups_with_perms(obj, attach_perms=False):
    """
    Returns queryset of all ``Group`` objects with *any* object permissions for
    the given ``obj``.

    :param obj: persisted Django's ``Model`` instance

    :param attach_perms: Default: ``False``. If set to ``True`` result would be
      dictionary of ``Group`` instances with permissions' codenames list as
      values. This would fetch groups eagerly!

    Example::

        >>> from django.contrib.flatpages.models import FlatPage
        >>> from guardian.shortcuts import assign_perm, get_groups_with_perms
        >>> from guardian.models import Group
        >>>
        >>> page = FlatPage.objects.create(title='Some page', path='/some/page/')
        >>> admins = Group.objects.create(name='Admins')
        >>> assign_perm('change_flatpage', admins, page)
        >>>
        >>> get_groups_with_perms(page)
        [<Group: admins>]
        >>>
        >>> get_groups_with_perms(page, attach_perms=True)
        {<Group: admins>: [u'change_flatpage']}

    """
    ctype = ContentType.objects.get_for_model(obj)
    if not attach_perms:
        # It's much easier without attached perms so we do it first if that is
        # the case
        group_model = get_group_obj_perms_model(obj)
        group_rel_name = group_model.group.field.related_query_name()
        if group_model.objects.is_generic():
            group_filters = {
                '%s__content_type' % group_rel_name: ctype,
                '%s__object_pk' % group_rel_name: obj.pk,
            }
        else:
            group_filters = {'%s__content_object' % group_rel_name: obj}
        groups = Group.objects.filter(**group_filters).distinct()
        return groups
    else:
        # TODO: Do not hit db for each group!
        groups = {}
        for group in get_groups_with_perms(obj):
            if not group in groups:
                groups[group] = sorted(get_perms(group, obj))
        return groups
def get_groups_with_perms(obj, attach_perms=False):
    """
    Returns queryset of all ``Group`` objects with *any* object permissions for
    the given ``obj``.

    :param obj: persisted Django's ``Model`` instance

    :param attach_perms: Default: ``False``. If set to ``True`` result would be
      dictionary of ``Group`` instances with permissions' codenames list as
      values. This would fetch groups eagerly!

    Example::

        >>> from django.contrib.flatpages.models import FlatPage
        >>> from guardian.shortcuts import assign_perm, get_groups_with_perms
        >>> from guardian.models import Group
        >>>
        >>> page = FlatPage.objects.create(title='Some page', path='/some/page/')
        >>> admins = Group.objects.create(name='Admins')
        >>> assign_perm('change_flatpage', admins, page)
        >>>
        >>> get_groups_with_perms(page)
        [<Group: admins>]
        >>>
        >>> get_groups_with_perms(page, attach_perms=True)
        {<Group: admins>: [u'change_flatpage']}

    """
    ctype = ContentType.objects.get_for_model(obj)
    if not attach_perms:
        # It's much easier without attached perms so we do it first if that is
        # the case
        group_model = get_group_obj_perms_model(obj)
        group_rel_name = group_model.group.field.related_query_name()
        if group_model.objects.is_generic():
            group_filters = {
                '%s__content_type' % group_rel_name: ctype,
                '%s__object_pk' % group_rel_name: obj.pk,
            }
        else:
            group_filters = {'%s__content_object' % group_rel_name: obj}
        groups = Group.objects.filter(**group_filters).distinct()
        return groups
    else:
        # TODO: Do not hit db for each group!
        groups = {}
        for group in get_groups_with_perms(obj):
            if not group in groups:
                groups[group] = sorted(get_perms(group, obj))
        return groups
Пример #12
0
def get_objects_for_group_using_content_type(group, codenames, ctype):
    codenames_set = set()

    if isinstance(codenames, basestring):
        codenames = [codenames]

    for codename in codenames:
        codenames_set.add(codename)

    queryset = _get_queryset(ctype.model_class())
    group_model = get_group_obj_perms_model(queryset.model)

    if isinstance(group, list):
        groups_obj_perms_queryset = (
            group_model.objects
            .filter(group__in=group)
            .filter(permission__content_type=ctype)
            .filter(permission__codename__in=codenames_set))
    else:
        groups_obj_perms_queryset = (
            group_model.objects
            .filter(group=group)
            .filter(permission__content_type=ctype)
            .filter(permission__codename__in=codenames_set))
    if group_model.objects.is_generic():
        fields = ['object_pk', 'permission__codename']
    else:
        fields = ['content_object__pk', 'permission__codename']
    groups_obj_perms = groups_obj_perms_queryset.values_list(*fields)
    data = list(groups_obj_perms)

    keyfunc = lambda t: t[0]  # sorting/grouping by pk (first in result tuple)
    data = sorted(data, key=keyfunc)
    pk_list = []
    for pk, group in groupby(data, keyfunc):
        obj_codenames = set((e[1] for e in group))
        if codenames_set.issubset(obj_codenames):
            pk_list.append(pk)

    objects = queryset.filter(pk__in=pk_list)
    return objects
Пример #13
0
    def _prefetch_cache(self):
        from guardian.utils import get_user_obj_perms_model, get_group_obj_perms_model
        UserObjectPermission = get_user_obj_perms_model()
        GroupObjectPermission = get_group_obj_perms_model()
        if self.user:
            obj = self.user
            querysets = [
                UserObjectPermission.objects.filter(user=obj),
                GroupObjectPermission.objects.filter(group__user=obj)
            ]
        else:
            obj = self.group
            querysets = [
                GroupObjectPermission.objects.filter(group=obj),
            ]

        if not hasattr(obj, '_guardian_perms_cache'):
            obj, cache = self._init_obj_prefetch_cache(obj, *querysets)
        else:
            cache = obj._guardian_perms_cache
        self._obj_perms_cache = cache
Пример #14
0
def get_groups_with_perms(obj, only_with_perms_in):
    ctype = get_content_type(obj)
    group_model = get_group_obj_perms_model(obj)

    group_rel_name = group_model.group.field.related_query_name()

    if group_model.objects.is_generic():
        group_filters = {
            "%s__content_type" % group_rel_name: ctype,
            "%s__object_pk" % group_rel_name: obj.pk,
        }
    else:
        group_filters = {"%s__content_object" % group_rel_name: obj}

    permission_ids = Permission.objects.filter(
        content_type=ctype, codename__in=only_with_perms_in
    ).values_list("id", flat=True)
    group_filters.update(
        {
            "%s__permission_id__in" % group_rel_name: permission_ids,
        }
    )
    return Group.objects.filter(**group_filters).distinct()
Пример #15
0
    def get_group_filters(self, obj):
        User = get_user_model()
        ctype = ContentType.objects.get_for_model(obj)

        group_model = get_group_obj_perms_model(obj)
        group_rel_name = group_model.permission.field.related_query_name()
        if self.user:
            fieldname = '%s__group__%s' % (
                group_rel_name,
                User.groups.field.related_query_name(),
            )
            group_filters = {fieldname: self.user}
        else:
            group_filters = {'%s__group' % group_rel_name: self.group}
        if group_model.objects.is_generic():
            group_filters.update({
                '%s__content_type' % group_rel_name: ctype,
                '%s__object_pk' % group_rel_name: obj.pk,
            })
        else:
            group_filters['%s__content_object' % group_rel_name] = obj

        return group_filters
Пример #16
0
    def get_group_filters(self, obj):
        User = get_user_model()
        ctype = get_content_type(obj)

        group_model = get_group_obj_perms_model(obj)
        group_rel_name = group_model.permission.field.related_query_name()
        if self.user:
            fieldname = '%s__group__%s' % (
                group_rel_name,
                User.groups.field.related_query_name(),
            )
            group_filters = {fieldname: self.user}
        else:
            group_filters = {'%s__group' % group_rel_name: self.group}
        if group_model.objects.is_generic():
            group_filters.update({
                '%s__content_type' % group_rel_name: ctype,
                '%s__object_pk' % group_rel_name: obj.pk,
            })
        else:
            group_filters['%s__content_object' % group_rel_name] = obj

        return group_filters
Пример #17
0
 def test_for_instance(self):
     project = Project(name='Foobar')
     self.assertEqual(get_group_obj_perms_model(project),
                      ProjectGroupObjectPermission)
Пример #18
0
from django.core.cache import cache
from django.db.models import Count, Q, QuerySet
from django.shortcuts import _get_queryset
from django.db.models.functions import Cast
from django.db.models import (IntegerField, AutoField, BigIntegerField,
                              PositiveIntegerField, PositiveSmallIntegerField,
                              SmallIntegerField, ForeignKey)
from pytz import utc

from guardian.core import ObjectPermissionChecker
from guardian.ctypes import get_content_type
from guardian.exceptions import MixedContentTypeError, WrongAppError, MultipleIdentityAndObjectError
from guardian.utils import get_anonymous_user, get_group_obj_perms_model, get_identity, get_user_obj_perms_model, \
    get_organization_obj_perms_model

OrganizationObjectPermission = get_group_obj_perms_model()
GroupObjectPermission = get_group_obj_perms_model()
UserObjectPermission = get_user_obj_perms_model()


def assign_perm(perm,
                user_or_group,
                obj=None,
                renewal_period=None,
                subscribe_to_emails=None):
    """
    Assigns permission to user/group and object pair.

    :param perm: proper permission for given ``obj``, as string (in format:
      ``app_label.codename`` or ``codename``) or ``Permission`` instance.
      If ``obj`` is not given, must be in format ``app_label.codename`` or
Пример #19
0
    def get_perms(self, obj):
        """
        Returns list of ``codename``'s of all permissions for given ``obj``.

        :param obj: Django model instance for which permission should be checked

        """
        User = get_user_model()
        ctype = ContentType.objects.get_for_model(obj)
        key = self.get_local_cache_key(obj)
        if not key in self._obj_perms_cache:

            group_model = get_group_obj_perms_model(obj)
            group_rel_name = group_model.permission.field.related_query_name()
            if self.user:
                fieldname = "%s__group__%s" % (group_rel_name, User.groups.field.related_query_name())
                group_filters = {fieldname: self.user}
            else:
                group_filters = {"%s__group" % group_rel_name: self.group}
            if group_model.objects.is_generic():
                group_filters.update(
                    {"%s__content_type" % group_rel_name: ctype, "%s__object_pk" % group_rel_name: obj.pk}
                )
            else:
                group_filters["%s__content_object" % group_rel_name] = obj

            if self.user and not self.user.is_active:
                return []
            elif self.user and self.user.is_superuser:
                perms = list(chain(*Permission.objects.filter(content_type=ctype).values_list("codename")))
            elif self.user:
                model = get_user_obj_perms_model(obj)
                related_name = model.permission.field.related_query_name()
                user_filters = {"%s__user" % related_name: self.user}
                if model.objects.is_generic():
                    user_filters.update(
                        {"%s__content_type" % related_name: ctype, "%s__object_pk" % related_name: obj.pk}
                    )
                else:
                    user_filters["%s__content_object" % related_name] = obj

                perms = list(
                    set(
                        chain(
                            *Permission.objects.filter(content_type=ctype)
                            .filter(Q(**user_filters) | Q(**group_filters))
                            .values_list("codename")
                        )
                    )
                )
            else:
                perms = list(
                    set(
                        chain(
                            *Permission.objects.filter(content_type=ctype)
                            .filter(**group_filters)
                            .values_list("codename")
                        )
                    )
                )
            self._obj_perms_cache[key] = perms
        return self._obj_perms_cache[key]
Пример #20
0
    def get_perms(self, obj):
        """
        Returns list of ``codename``'s of all permissions for given ``obj``.

        :param obj: Django model instance for which permission should be checked

        """
        User = get_user_model()
        ctype = ContentType.objects.get_for_model(obj)
        key = self.get_local_cache_key(obj)
        if not key in self._obj_perms_cache:

            group_model = get_group_obj_perms_model(obj)
            group_rel_name = group_model.permission.field.related_query_name()
            if self.user:
                fieldname = '%s__group__%s' % (
                    group_rel_name,
                    User.groups.field.related_query_name(),
                )
                group_filters = {fieldname: self.user}
            else:
                group_filters = {'%s__group' % group_rel_name: self.group}
            if group_model.objects.is_generic():
                group_filters.update({
                    '%s__content_type' % group_rel_name: ctype,
                    '%s__object_pk' % group_rel_name: obj.pk,
                })
            else:
                group_filters['%s__content_object' % group_rel_name] = obj

            if self.user and not self.user.is_active:
                return []
            elif self.user and self.user.is_superuser:
                perms = list(
                    chain(*Permission.objects.filter(
                        content_type=ctype).values_list("codename")))
            elif self.user:
                model = get_user_obj_perms_model(obj)
                related_name = model.permission.field.related_query_name()
                user_filters = {'%s__user' % related_name: self.user}
                if model.objects.is_generic():
                    user_filters.update({
                        '%s__content_type' % related_name: ctype,
                        '%s__object_pk' % related_name: obj.pk,
                    })
                else:
                    user_filters['%s__content_object' % related_name] = obj

                perms = list(
                    set(
                        chain(*Permission.objects.filter(content_type=ctype).
                              filter(Q(**user_filters) | Q(
                                  **group_filters)).values_list("codename"))))
            else:
                perms = list(
                    set(
                        chain(*Permission.objects.filter(
                            content_type=ctype).filter(
                                **group_filters).values_list("codename"))))
            self._obj_perms_cache[key] = perms
        return self._obj_perms_cache[key]
def get_objects_for_user(user, perms, klass=None, use_groups=True, any_perm=False,
        with_superuser=True, accept_global_perms=True):
    """
    Returns queryset of objects for which a given ``user`` has *all*
    permissions present at ``perms``.

    If ``perms`` is an empty list, then it returns objects for which
    a given ``user`` has *any* object permission.

    :param user: ``User`` or ``AnonymousUser`` instance for which objects would
      be returned.
    :param perms: single permission string, or sequence of permission strings
      which should be checked.
      If ``klass`` parameter is not given, those should be full permission
      names rather than only codenames (i.e. ``auth.change_user``). If more than
      one permission is present within sequence, their content type **must** be
      the same or ``MixedContentTypeError`` exception would be raised.
    :param klass: may be a Model, Manager or QuerySet object. If not given
      this parameter would be computed based on given ``params``.
    :param use_groups: if ``False``, wouldn't check user's groups object
      permissions. Default is ``True``.
    :param any_perm: if True, any of permission in sequence is accepted. Default is ``False``.
    :param with_superuser: if ``True`` and if ``user.is_superuser`` is set,
      returns the entire queryset. Otherwise will only return objects the user
      has explicit permissions. This must be ``True`` for the accept_global_perms
      parameter to have any affect. Default is ``True``.
    :param accept_global_perms: if ``True`` takes global permissions into account.
      Object based permissions are taken into account if more than one permission is handed in in perms and at least
      one of these perms is not globally set. If any_perm is set to false then the intersection of matching object
      is returned. Note, that if with_superuser is False, accept_global_perms will be ignored, which means that only
      object permissions will be checked! Default is ``True``.

    :raises MixedContentTypeError: when computed content type for ``perms``
      and/or ``klass`` clashes.
    :raises WrongAppError: if cannot compute app label for given ``perms``/
      ``klass``.

    Example::

        >>> from django.contrib.auth.models import User
        >>> from guardian.shortcuts import get_objects_for_user
        >>> joe = User.objects.get(username='******')
        >>> get_objects_for_user(joe, 'auth.change_group')
        []
        >>> from guardian.shortcuts import assign_perm
        >>> group = Group.objects.create('some group')
        >>> assign_perm('auth.change_group', joe, group)
        >>> get_objects_for_user(joe, 'auth.change_group')
        [<Group some group>]


    The permission string can also be an iterable. Continuing with the previous example:

        >>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'])
        []
        >>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'], any_perm=True)
        [<Group some group>]
        >>> assign_perm('auth.delete_group', joe, group)
        >>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'])
        [<Group some group>]

    Take global permissions into account:

        >>> jack = User.objects.get(username='******')
        >>> assign_perm('auth.change_group', jack) # this will set a global permission
        >>> get_objects_for_user(jack, 'auth.change_group')
        [<Group some group>]
        >>> group2 = Group.objects.create('other group')
        >>> assign_perm('auth.delete_group', jack, group2)
        >>> get_objects_for_user(jack, ['auth.change_group', 'auth.delete_group']) # this retrieves intersection
        [<Group other group>]
        >>> get_objects_for_user(jack, ['auth.change_group', 'auth.delete_group'], any_perm) # this retrieves union
        [<Group some group>, <Group other group>]

    If accept_global_perms is set to ``True``, then all assigned global
    permissions will also be taken into account.

    - Scenario 1: a user has view permissions generally defined on the model
      'books' but no object based permission on a single book instance:

        - If accept_global_perms is ``True``: List of all books will be
          returned.
        - If accept_global_perms is ``False``: list will be empty.

    - Scenario 2: a user has view permissions generally defined on the model
      'books' and also has an object based permission to view book 'Whatever':

        - If accept_global_perms is ``True``: List of all books will be
          returned.
        - If accept_global_perms is ``False``: list will only contain book
          'Whatever'.

    - Scenario 3: a user only has object based permission on book 'Whatever':

        - If accept_global_perms is ``True``: List will only contain book
          'Whatever'.
        - If accept_global_perms is ``False``: List will only contain book
          'Whatever'.

    - Scenario 4: a user does not have any permission:

        - If accept_global_perms is ``True``: Empty list.
        - If accept_global_perms is ``False``: Empty list.
    """
    if isinstance(perms, basestring):
        perms = [perms]
    ctype = None
    app_label = None
    codenames = set()

    # Compute codenames set and ctype if possible
    for perm in perms:
        if '.' in perm:
            new_app_label, codename = perm.split('.', 1)
            if app_label is not None and app_label != new_app_label:
                raise MixedContentTypeError("Given perms must have same app "
                    "label (%s != %s)" % (app_label, new_app_label))
            else:
                app_label = new_app_label
        else:
            codename = perm
        codenames.add(codename)
        if app_label is not None:
            new_ctype = ContentType.objects.get(app_label=app_label,
                permission__codename=codename)
            if ctype is not None and ctype != new_ctype:
                raise MixedContentTypeError("ContentType was once computed "
                    "to be %s and another one %s" % (ctype, new_ctype))
            else:
                ctype = new_ctype

    # Compute queryset and ctype if still missing
    if ctype is None and klass is not None:
        queryset = _get_queryset(klass)
        ctype = ContentType.objects.get_for_model(queryset.model)
    elif ctype is not None and klass is None:
        queryset = _get_queryset(ctype.model_class())
    elif klass is None:
        raise WrongAppError("Cannot determine content type")
    else:
        queryset = _get_queryset(klass)
        if ctype.model_class() != queryset.model:
            raise MixedContentTypeError("Content type for given perms and "
                "klass differs")

    # At this point, we should have both ctype and queryset and they should
    # match which means: ctype.model_class() == queryset.model
    # we should also have ``codenames`` list

    # First check if user is superuser and if so, return queryset immediately
    if with_superuser and user.is_superuser:
        return queryset

    # Check if the user is anonymous. The
    # django.contrib.auth.models.AnonymousUser object doesn't work for queries
    # and it's nice to be able to pass in request.user blindly.
    if user.is_anonymous():
        user = get_anonymous_user()

    global_perms = set()
    has_global_perms = False
    # a superuser has by default assigned global perms for any
    if accept_global_perms and with_superuser:
        for code in codenames:
            if user.has_perm(ctype.app_label + '.' + code):
                global_perms.add(code)
        for code in global_perms:
            codenames.remove(code)
        ## prerequisite: there must be elements in global_perms otherwise just follow the procedure for
        # object based permissions only AND
        # 1. codenames is empty, which means that permissions are ONLY set globally, therefore return the full queryset.
        # OR
        # 2. any_perm is True, then the global permission beats the object based permission anyway,
        # therefore return full queryset
        if len(global_perms) > 0 and (len(codenames) == 0 or any_perm):
            return queryset
        # if we have global perms and still some object based perms differing from global perms and any_perm is set
        # to false, then we have to flag that global perms exist in order to merge object based permissions by user
        # and by group correctly. Scenario: global perm change_xx and object based perm delete_xx on object A for user,
        # and object based permission delete_xx  on object B for group, to which user is assigned.
        # get_objects_for_user(user, [change_xx, delete_xx], use_groups=True, any_perm=False, accept_global_perms=True)
        # must retrieve object A and B.
        elif len(global_perms) > 0 and (len(codenames) > 0):
            has_global_perms = True


    # Now we should extract list of pk values for which we would filter queryset
    user_model = get_user_obj_perms_model(queryset.model)
    user_obj_perms_queryset = (user_model.objects
        .filter(user=user)
        .filter(permission__content_type=ctype))
    if len(codenames):
        user_obj_perms_queryset = user_obj_perms_queryset.filter(permission__codename__in=codenames)
    if user_model.objects.is_generic():
        fields = ['object_pk', 'permission__codename']
    else:
        fields = ['content_object__pk', 'permission__codename']

    if use_groups:
        group_model = get_group_obj_perms_model(queryset.model)
        group_filters = {
            'permission__content_type': ctype,
            'group__%s' % get_user_model().groups.field.related_query_name(): user,
        }
        if len(codenames):
            group_filters.update({
                'permission__codename__in': codenames,
            })
        groups_obj_perms_queryset = group_model.objects.filter(**group_filters)
        if group_model.objects.is_generic():
            fields = ['object_pk', 'permission__codename']
        else:
            fields = ['content_object__pk', 'permission__codename']
        if not any_perm and len(codenames) and not has_global_perms:
            user_obj_perms = user_obj_perms_queryset.values_list(*fields)
            groups_obj_perms = groups_obj_perms_queryset.values_list(*fields)
            data = list(user_obj_perms) + list(groups_obj_perms)
            keyfunc = lambda t: t[0] # sorting/grouping by pk (first in result tuple)
            data = sorted(data, key=keyfunc)
            pk_list = []
            for pk, group in groupby(data, keyfunc):
                obj_codenames = set((e[1] for e in group))
                if codenames.issubset(obj_codenames):
                    pk_list.append(pk)
            objects = queryset.filter(pk__in=pk_list)
            return objects

    if not any_perm and len(codenames) > 1:
        counts = user_obj_perms_queryset.values(fields[0]).annotate(object_pk_count=Count(fields[0]))
        user_obj_perms_queryset = counts.filter(object_pk_count__gte=len(codenames))

    values = user_obj_perms_queryset.values_list(fields[0], flat=True)
    if user_model.objects.is_generic():
        values = list(values)
    objects = queryset.filter(pk__in=values)
    if use_groups:
        values = groups_obj_perms_queryset.values_list(fields[0], flat=True)
        if group_model.objects.is_generic():
            values = list(values)
        objects |= queryset.filter(pk__in=values)

    return objects
Пример #22
0
 def test_for_instance(self):
     project = Project(name='Foobar')
     self.assertEqual(get_group_obj_perms_model(project),
         ProjectGroupObjectPermission)
Пример #23
0
 def test_for_class(self):
     self.assertEqual(get_group_obj_perms_model(Project),
         ProjectGroupObjectPermission)
Пример #24
0
def assign_perm(perm, user_or_group, obj=None):
    """
    Assigns permission to user/group and object pair.

    :param perm: proper permission for given ``obj``, as string (in format:
      ``app_label.codename`` or ``codename``) or ``Permission`` instance.
      If ``obj`` is not given, must be in format ``app_label.codename`` or
      ``Permission`` instance.

    :param user_or_group: instance of ``User``, ``AnonymousUser`` or ``Group``;
      passing any other object would raise
      ``guardian.exceptions.NotUserNorGroup`` exception

    :param obj: persisted Django's ``Model`` instance or QuerySet of Django
      ``Model`` instances or ``None`` if assigning global permission.
      Default is ``None``.

    We can assign permission for ``Model`` instance for specific user:

    >>> from django.contrib.sites.models import Site
    >>> from guardian.models import User
    >>> from guardian.shortcuts import assign_perm
    >>> site = Site.objects.get_current()
    >>> user = User.objects.create(username='******')
    >>> assign_perm("change_site", user, site)
    <UserObjectPermission: example.com | joe | change_site>
    >>> user.has_perm("change_site", site)
    True

    ... or we can assign permission for group:

    >>> group = Group.objects.create(name='joe-group')
    >>> user.groups.add(group)
    >>> assign_perm("delete_site", group, site)
    <GroupObjectPermission: example.com | joe-group | delete_site>
    >>> user.has_perm("delete_site", site)
    True

    **Global permissions**

    This function may also be used to assign standard, *global* permissions if
    ``obj`` parameter is omitted. Added Permission would be returned in that
    case:

    >>> assign_perm("sites.change_site", user)
    <Permission: sites | site | Can change site>

    """

    user, group = get_identity(user_or_group)
    # If obj is None we try to operate on global permissions
    if obj is None:
        if not isinstance(perm, Permission):
            try:
                app_label, codename = perm.split('.', 1)
            except ValueError:
                raise ValueError(
                    "For global permissions, first argument must be in"
                    " format: 'app_label.codename' (is %r)" % perm)
            perm = Permission.objects.get(content_type__app_label=app_label,
                                          codename=codename)

        if user:
            user.user_permissions.add(perm)
            return perm
        if group:
            group.permissions.add(perm)
            return perm

    if not isinstance(perm, Permission):
        perm = perm.split('.')[-1]

    if isinstance(obj, QuerySet):
        if user:
            model = get_user_obj_perms_model(obj.model)
            return model.objects.bulk_assign_perm(perm, user, obj)
        if group:
            model = get_group_obj_perms_model(obj.model)
            return model.objects.bulk_assign_perm(perm, group, obj)

    if user:
        model = get_user_obj_perms_model(obj)
        return model.objects.assign_perm(perm, user, obj)

    if group:
        model = get_group_obj_perms_model(obj)
        return model.objects.assign_perm(perm, group, obj)
Пример #25
0
    def prefetch_perms(self, objects):
        """
        Prefetches the permissions for objects in ``objects`` and puts them in the cache.

        :param objects: Iterable of Django model objects

        """
        if self.user and not self.user.is_active:
            return []

        User = get_user_model()
        pks, model, ctype = _get_pks_model_and_ctype(objects)

        if self.user and self.user.is_superuser:
            perms = list(chain(
                *Permission.objects
                .filter(content_type=ctype)
                .values_list("codename")))

            for pk in pks:
                key = (ctype.id, force_text(pk))
                self._obj_perms_cache[key] = perms

            return True

        group_model = get_group_obj_perms_model(model)

        group_filters = {
            'object_pk__in': pks
        }

        if self.user:
            fieldname = 'group__%s' % (
                User.groups.field.related_query_name(),
            )
            group_filters.update({fieldname: self.user})
        else:
            group_filters = {'group': self.group}

        if group_model.objects.is_generic():
            group_filters.update({
                'content_type': ctype,
            })

        if self.user:
            model = get_user_obj_perms_model(model)
            user_filters = {
                'user': self.user,
                'object_pk__in': pks
            }

            if model.objects.is_generic():
                user_filters.update({
                    'content_type': ctype,
                })

            # Query user and group permissions separately and then combine
            # the results to avoid a slow query
            user_perms_qs = model.objects.filter(**user_filters).select_related('permission')
            group_perms_qs = group_model.objects.filter(**group_filters).select_related('permission')
            perms = chain(user_perms_qs, group_perms_qs)
        else:
            perms = chain(
                *(group_model.objects.filter(**group_filters).select_related('permission'),)
            )

        for perm in perms:
            key = (ctype.id, perm.object_pk)

            if key in self._obj_perms_cache:
                self._obj_perms_cache[key].append(perm.permission.codename)
            else:
                self._obj_perms_cache[key] = [perm.permission.codename]

        return True
Пример #26
0
 def test_for_class(self):
     self.assertEqual(get_group_obj_perms_model(Project),
                      ProjectGroupObjectPermission)
Пример #27
0
 def test_default(self):
     self.assertEqual(get_group_obj_perms_model(ContentType),
                      GroupObjectPermission)
Пример #28
0
def get_users_with_perms(obj,
                         attach_perms=False,
                         with_superusers=False,
                         with_group_users=True,
                         only_with_perms_in=None):
    """
    Returns queryset of all ``User`` objects with *any* object permissions for
    the given ``obj``.

    :param obj: persisted Django's ``Model`` instance

    :param attach_perms: Default: ``False``. If set to ``True`` result would be
      dictionary of ``User`` instances with permissions' codenames list as
      values. This would fetch users eagerly!

    :param with_superusers: Default: ``False``. If set to ``True`` result would
      contain all superusers.

    :param with_group_users: Default: ``True``. If set to ``False`` result would
      **not** contain those users who have only group permissions for given
      ``obj``.

    :param only_with_perms_in: Default: ``None``. If set to an iterable of
      permission strings then only users with those permissions would be
      returned.

    Example::

        >>> from django.contrib.flatpages.models import FlatPage
        >>> from django.contrib.auth.models import User
        >>> from guardian.shortcuts import assign_perm, get_users_with_perms
        >>>
        >>> page = FlatPage.objects.create(title='Some page', path='/some/page/')
        >>> joe = User.objects.create_user('joe', '*****@*****.**', 'joesecret')
        >>> dan = User.objects.create_user('dan', '*****@*****.**', 'dansecret')
        >>> assign_perm('change_flatpage', joe, page)
        >>> assign_perm('delete_flatpage', dan, page)
        >>>
        >>> get_users_with_perms(page)
        [<User: joe>, <User: dan>]
        >>>
        >>> get_users_with_perms(page, attach_perms=True)
        {<User: joe>: [u'change_flatpage'], <User: dan>: [u'delete_flatpage']}
        >>> get_users_with_perms(page, only_with_perms_in=['change_flatpage'])
        [<User: joe>]

    """
    ctype = get_content_type(obj)
    if not attach_perms:
        # It's much easier without attached perms so we do it first if that is
        # the case
        user_model = get_user_obj_perms_model(obj)
        related_name = user_model.user.field.related_query_name()
        if user_model.objects.is_generic():
            user_filters = {
                '%s__content_type' % related_name: ctype,
                '%s__object_pk' % related_name: obj.pk,
            }
        else:
            user_filters = {'%s__content_object' % related_name: obj}
        qset = Q(**user_filters)
        if only_with_perms_in is not None:
            permission_ids = Permission.objects.filter(
                content_type=ctype,
                codename__in=only_with_perms_in).values_list('id', flat=True)
            qset &= Q(**{
                '%s__permission_id__in' % related_name: permission_ids,
            })
        if with_group_users:
            group_model = get_group_obj_perms_model(obj)
            if group_model.objects.is_generic():
                group_obj_perm_filters = {
                    'content_type': ctype,
                    'object_pk': obj.pk,
                }
            else:
                group_obj_perm_filters = {
                    'content_object': obj,
                }
            if only_with_perms_in is not None:
                group_obj_perm_filters.update({
                    'permission_id__in':
                    permission_ids,
                })
            group_ids = set(
                group_model.objects.filter(
                    **group_obj_perm_filters).values_list(
                        'group_id', flat=True).distinct())
            qset = qset | Q(groups__in=group_ids)
        if with_superusers:
            qset = qset | Q(is_superuser=True)
        return get_user_model().objects.filter(qset).distinct()
    else:
        # TODO: Do not hit db for each user!
        users = {}
        for user in get_users_with_perms(obj,
                                         with_group_users=with_group_users,
                                         only_with_perms_in=only_with_perms_in,
                                         with_superusers=with_superusers):
            # TODO: Support the case of set with_group_users but not with_superusers.
            if with_group_users or with_superusers:
                users[user] = sorted(get_perms(user, obj))
            else:
                users[user] = sorted(get_user_perms(user, obj))
        return users
Пример #29
0
from django.db.models import Count, Q, QuerySet
from django.shortcuts import _get_queryset
from django.db.models.functions import Cast
from django.db.models import (
    IntegerField,
    AutoField,
    BigIntegerField,
    PositiveIntegerField,
    PositiveSmallIntegerField,
    SmallIntegerField,
)
from guardian.core import ObjectPermissionChecker
from guardian.ctypes import get_content_type
from guardian.exceptions import MixedContentTypeError, WrongAppError, MultipleIdentityAndObjectError
from guardian.utils import get_anonymous_user, get_group_obj_perms_model, get_identity, get_user_obj_perms_model
GroupObjectPermission = get_group_obj_perms_model()
UserObjectPermission = get_user_obj_perms_model()


def assign_perm(perm, user_or_group, obj=None):
    """
    Assigns permission to user/group and object pair.

    :param perm: proper permission for given ``obj``, as string (in format:
      ``app_label.codename`` or ``codename``) or ``Permission`` instance.
      If ``obj`` is not given, must be in format ``app_label.codename`` or
      ``Permission`` instance.

    :param user_or_group: instance of ``User``, ``AnonymousUser``, ``Group``,
      list of ``User`` or ``Group``, or queryset of ``User`` or ``Group``;
      passing any other object would raise
Пример #30
0
def get_objects_for_user(user, perms, klass=None, use_groups=True, any_perm=False,
                         with_superuser=True, accept_global_perms=True, perms_filter='pk__in'):
    """Return queryset with required permissions."""
    if isinstance(perms, str):
        perms = [perms]

    ctype = None
    app_label = None
    codenames = set()

    # Compute codenames set and ctype if possible
    for perm in perms:
        if '.' in perm:
            new_app_label, codename = perm.split('.', 1)
            if app_label is not None and app_label != new_app_label:
                raise MixedContentTypeError(
                    "Given perms must have same app label "
                    "({} != {})".format(app_label, new_app_label))
            else:
                app_label = new_app_label
        else:
            codename = perm
        codenames.add(codename)

        if app_label is not None:
            new_ctype = ContentType.objects.get(app_label=app_label,
                                                permission__codename=codename)
            if ctype is not None and ctype != new_ctype:
                raise MixedContentTypeError(
                    "ContentType was once computed to be {} and another "
                    "one {}".format(ctype, new_ctype))
            else:
                ctype = new_ctype

    # Compute queryset and ctype if still missing
    if ctype is None and klass is not None:
        queryset = _get_queryset(klass)
        ctype = ContentType.objects.get_for_model(queryset.model)
    elif ctype is not None and klass is None:
        queryset = _get_queryset(ctype.model_class())
    elif klass is None:
        raise WrongAppError("Cannot determine content type")
    else:
        queryset = _get_queryset(klass)
        if ctype.model_class() != queryset.model and perms_filter == 'pk__in':
            raise MixedContentTypeError("Content type for given perms and "
                                        "klass differs")

    # At this point, we should have both ctype and queryset and they should
    # match which means: ctype.model_class() == queryset.model
    # we should also have `codenames` list

    # First check if user is superuser and if so, return queryset immediately
    if with_superuser and user.is_superuser:
        return queryset

    # Check if the user is anonymous. The
    # django.contrib.auth.models.AnonymousUser object doesn't work for queries
    # and it's nice to be able to pass in request.user blindly.
    if user.is_anonymous:
        user = get_anonymous_user()

    global_perms = set()
    has_global_perms = False
    # a superuser has by default assigned global perms for any
    if accept_global_perms and with_superuser:
        for code in codenames:
            if user.has_perm(ctype.app_label + '.' + code):
                global_perms.add(code)
        for code in global_perms:
            codenames.remove(code)
        # prerequisite: there must be elements in global_perms otherwise just
        # follow the procedure for object based permissions only AND
        # 1. codenames is empty, which means that permissions are ONLY set
        # globally, therefore return the full queryset.
        # OR
        # 2. any_perm is True, then the global permission beats the object
        # based permission anyway, therefore return full queryset
        if global_perms and (not codenames or any_perm):
            return queryset
        # if we have global perms and still some object based perms differing
        # from global perms and any_perm is set to false, then we have to flag
        # that global perms exist in order to merge object based permissions by
        # user and by group correctly. Scenario: global perm change_xx and
        # object based perm delete_xx on object A for user, and object based
        # permission delete_xx  on object B for group, to which user is
        # assigned.
        # get_objects_for_user(user, [change_xx, delete_xx], use_groups=True,
        # any_perm=False, accept_global_perms=True) must retrieve object A and
        # B.
        elif global_perms and codenames:
            has_global_perms = True

    # Now we should extract list of pk values for which we would filter
    # queryset
    user_model = get_user_obj_perms_model(queryset.model)
    user_obj_perms_queryset = (user_model.objects
                               .filter(Q(user=user) | Q(user=get_anonymous_user()))
                               .filter(permission__content_type=ctype))

    if codenames:
        user_obj_perms_queryset = user_obj_perms_queryset.filter(
            permission__codename__in=codenames)
    direct_fields = ['content_object__pk', 'permission__codename']
    generic_fields = ['object_pk', 'permission__codename']
    if user_model.objects.is_generic():
        user_fields = generic_fields
    else:
        user_fields = direct_fields

    if use_groups:
        group_model = get_group_obj_perms_model(queryset.model)
        group_filters = {
            'permission__content_type': ctype,
            'group__{}'.format(get_user_model().groups.field.related_query_name()): user,
        }
        if codenames:
            group_filters.update({
                'permission__codename__in': codenames,
            })
        groups_obj_perms_queryset = group_model.objects.filter(**group_filters)
        if group_model.objects.is_generic():
            group_fields = generic_fields
        else:
            group_fields = direct_fields
        if not any_perm and codenames and not has_global_perms:
            user_obj_perms = user_obj_perms_queryset.values_list(*user_fields)
            groups_obj_perms = groups_obj_perms_queryset.values_list(*group_fields)
            data = list(user_obj_perms) + list(groups_obj_perms)
            # sorting/grouping by pk (first in result tuple)
            data = sorted(data, key=lambda t: t[0])
            pk_list = []
            for pk, group in groupby(data, lambda t: t[0]):
                obj_codenames = set((e[1] for e in group))
                if codenames.issubset(obj_codenames):
                    pk_list.append(pk)
            objects = queryset.filter(**{perms_filter: pk_list})
            return objects

    if not any_perm and len(codenames) > 1:
        counts = user_obj_perms_queryset.values(
            user_fields[0]).annotate(object_pk_count=Count(user_fields[0]))
        user_obj_perms_queryset = counts.filter(
            object_pk_count__gte=len(codenames))

    values = user_obj_perms_queryset.values_list(user_fields[0], flat=True)
    if user_model.objects.is_generic():
        values = list(values)
    query = Q(**{perms_filter: values})
    if use_groups:
        values = groups_obj_perms_queryset.values_list(group_fields[0], flat=True)
        if group_model.objects.is_generic():
            values = list(values)
        query |= Q(**{perms_filter: values})

    return queryset.filter(query)
Пример #31
0
 def test_default(self):
     self.assertEqual(get_group_obj_perms_model(ContentType),
         GroupObjectPermission)
Пример #32
0
def get_objects_for_user(user,
                         perms,
                         klass=None,
                         use_groups=True,
                         any_perm=False,
                         with_superuser=True,
                         accept_global_perms=True):
    """
    Returns queryset of objects for which a given ``user`` has *all*
    permissions present at ``perms``.

    If ``perms`` is an empty list, then it returns objects for which
    a given ``user`` has *any* object permission.

    :param user: ``User`` or ``AnonymousUser`` instance for which objects would
      be returned.
    :param perms: single permission string, or sequence of permission strings
      which should be checked.
      If ``klass`` parameter is not given, those should be full permission
      names rather than only codenames (i.e. ``auth.change_user``). If more than
      one permission is present within sequence, their content type **must** be
      the same or ``MixedContentTypeError`` exception would be raised.
    :param klass: may be a Model, Manager or QuerySet object. If not given
      this parameter would be computed based on given ``params``.
    :param use_groups: if ``False``, wouldn't check user's groups object
      permissions. Default is ``True``.
    :param any_perm: if True, any of permission in sequence is accepted. Default is ``False``.
    :param with_superuser: if ``True`` and if ``user.is_superuser`` is set,
      returns the entire queryset. Otherwise will only return objects the user
      has explicit permissions. This must be ``True`` for the accept_global_perms
      parameter to have any affect. Default is ``True``.
    :param accept_global_perms: if ``True`` takes global permissions into account.
      Object based permissions are taken into account if more than one permission is handed in in perms and at least
      one of these perms is not globally set. If any_perm is set to false then the intersection of matching object
      is returned. Note, that if with_superuser is False, accept_global_perms will be ignored, which means that only
      object permissions will be checked! Default is ``True``.

    :raises MixedContentTypeError: when computed content type for ``perms``
      and/or ``klass`` clashes.
    :raises WrongAppError: if cannot compute app label for given ``perms``/
      ``klass``.

    Example::

        >>> from django.contrib.auth.models import User
        >>> from guardian.shortcuts import get_objects_for_user
        >>> joe = User.objects.get(username='******')
        >>> get_objects_for_user(joe, 'auth.change_group')
        []
        >>> from guardian.shortcuts import assign_perm
        >>> group = Group.objects.create('some group')
        >>> assign_perm('auth.change_group', joe, group)
        >>> get_objects_for_user(joe, 'auth.change_group')
        [<Group some group>]


    The permission string can also be an iterable. Continuing with the previous example:

        >>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'])
        []
        >>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'], any_perm=True)
        [<Group some group>]
        >>> assign_perm('auth.delete_group', joe, group)
        >>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'])
        [<Group some group>]

    Take global permissions into account:

        >>> jack = User.objects.get(username='******')
        >>> assign_perm('auth.change_group', jack) # this will set a global permission
        >>> get_objects_for_user(jack, 'auth.change_group')
        [<Group some group>]
        >>> group2 = Group.objects.create('other group')
        >>> assign_perm('auth.delete_group', jack, group2)
        >>> get_objects_for_user(jack, ['auth.change_group', 'auth.delete_group']) # this retrieves intersection
        [<Group other group>]
        >>> get_objects_for_user(jack, ['auth.change_group', 'auth.delete_group'], any_perm) # this retrieves union
        [<Group some group>, <Group other group>]

    If accept_global_perms is set to ``True``, then all assigned global
    permissions will also be taken into account.

    - Scenario 1: a user has view permissions generally defined on the model
      'books' but no object based permission on a single book instance:

        - If accept_global_perms is ``True``: List of all books will be
          returned.
        - If accept_global_perms is ``False``: list will be empty.

    - Scenario 2: a user has view permissions generally defined on the model
      'books' and also has an object based permission to view book 'Whatever':

        - If accept_global_perms is ``True``: List of all books will be
          returned.
        - If accept_global_perms is ``False``: list will only contain book
          'Whatever'.

    - Scenario 3: a user only has object based permission on book 'Whatever':

        - If accept_global_perms is ``True``: List will only contain book
          'Whatever'.
        - If accept_global_perms is ``False``: List will only contain book
          'Whatever'.

    - Scenario 4: a user does not have any permission:

        - If accept_global_perms is ``True``: Empty list.
        - If accept_global_perms is ``False``: Empty list.
    """
    if isinstance(perms, basestring):
        perms = [perms]
    ctype = None
    app_label = None
    codenames = set()

    # Compute codenames set and ctype if possible
    for perm in perms:
        if '.' in perm:
            new_app_label, codename = perm.split('.', 1)
            if app_label is not None and app_label != new_app_label:
                raise MixedContentTypeError("Given perms must have same app "
                                            "label (%s != %s)" %
                                            (app_label, new_app_label))
            else:
                app_label = new_app_label
        else:
            codename = perm
        codenames.add(codename)
        if app_label is not None:
            new_ctype = ContentType.objects.get(app_label=app_label,
                                                permission__codename=codename)
            if ctype is not None and ctype != new_ctype:
                raise MixedContentTypeError("ContentType was once computed "
                                            "to be %s and another one %s" %
                                            (ctype, new_ctype))
            else:
                ctype = new_ctype

    # Compute queryset and ctype if still missing
    if ctype is None and klass is not None:
        queryset = _get_queryset(klass)
        ctype = get_content_type(queryset.model)
    elif ctype is not None and klass is None:
        queryset = _get_queryset(ctype.model_class())
    elif klass is None:
        raise WrongAppError("Cannot determine content type")
    else:
        queryset = _get_queryset(klass)
        if ctype.model_class() != queryset.model:
            raise MixedContentTypeError("Content type for given perms and "
                                        "klass differs")

    # At this point, we should have both ctype and queryset and they should
    # match which means: ctype.model_class() == queryset.model
    # we should also have ``codenames`` list

    # First check if user is superuser and if so, return queryset immediately
    if with_superuser and user.is_superuser:
        return queryset

    # Check if the user is anonymous. The
    # django.contrib.auth.models.AnonymousUser object doesn't work for queries
    # and it's nice to be able to pass in request.user blindly.
    if user.is_anonymous():
        user = get_anonymous_user()

    global_perms = set()
    has_global_perms = False
    # a superuser has by default assigned global perms for any
    if accept_global_perms and with_superuser:
        for code in codenames:
            if user.has_perm(ctype.app_label + '.' + code):
                global_perms.add(code)
        for code in global_perms:
            codenames.remove(code)
        # prerequisite: there must be elements in global_perms otherwise just follow the procedure for
        # object based permissions only AND
        # 1. codenames is empty, which means that permissions are ONLY set globally, therefore return the full queryset.
        # OR
        # 2. any_perm is True, then the global permission beats the object based permission anyway,
        # therefore return full queryset
        if len(global_perms) > 0 and (len(codenames) == 0 or any_perm):
            return queryset
        # if we have global perms and still some object based perms differing from global perms and any_perm is set
        # to false, then we have to flag that global perms exist in order to merge object based permissions by user
        # and by group correctly. Scenario: global perm change_xx and object based perm delete_xx on object A for user,
        # and object based permission delete_xx  on object B for group, to which user is assigned.
        # get_objects_for_user(user, [change_xx, delete_xx], use_groups=True, any_perm=False, accept_global_perms=True)
        # must retrieve object A and B.
        elif len(global_perms) > 0 and (len(codenames) > 0):
            has_global_perms = True

    # Now we should extract list of pk values for which we would filter
    # queryset
    user_model = get_user_obj_perms_model(queryset.model)
    user_obj_perms_queryset = (user_model.objects.filter(user=user).filter(
        permission__content_type=ctype))
    if len(codenames):
        user_obj_perms_queryset = user_obj_perms_queryset.filter(
            permission__codename__in=codenames)
    direct_fields = ['content_object__pk', 'permission__codename']
    generic_fields = ['object_pk', 'permission__codename']
    if user_model.objects.is_generic():
        user_fields = generic_fields
    else:
        user_fields = direct_fields

    if use_groups:
        group_model = get_group_obj_perms_model(queryset.model)
        group_filters = {
            'permission__content_type': ctype,
            'group__%s' % get_user_model().groups.field.related_query_name():
            user,
        }
        if len(codenames):
            group_filters.update({
                'permission__codename__in': codenames,
            })
        groups_obj_perms_queryset = group_model.objects.filter(**group_filters)
        if group_model.objects.is_generic():
            group_fields = generic_fields
        else:
            group_fields = direct_fields
        if not any_perm and len(codenames) > 1 and not has_global_perms:
            user_obj_perms = user_obj_perms_queryset.values_list(*user_fields)
            groups_obj_perms = groups_obj_perms_queryset.values_list(
                *group_fields)
            data = list(user_obj_perms) + list(groups_obj_perms)
            # sorting/grouping by pk (first in result tuple)
            keyfunc = lambda t: t[0]
            data = sorted(data, key=keyfunc)
            pk_list = []
            for pk, group in groupby(data, keyfunc):
                obj_codenames = set((e[1] for e in group))
                if codenames.issubset(obj_codenames):
                    pk_list.append(pk)
            objects = queryset.filter(pk__in=pk_list)
            return objects

    if not any_perm and len(codenames) > 1:
        counts = user_obj_perms_queryset.values(
            user_fields[0]).annotate(object_pk_count=Count(user_fields[0]))
        user_obj_perms_queryset = counts.filter(
            object_pk_count__gte=len(codenames))

    values = user_obj_perms_queryset.values_list(user_fields[0], flat=True)
    if user_model.objects.is_generic():
        values = set(values)
    q = Q(pk__in=values)
    if use_groups:
        values = groups_obj_perms_queryset.values_list(group_fields[0],
                                                       flat=True)
        if group_model.objects.is_generic():
            values = set(values)
        q |= Q(pk__in=values)

    return queryset.filter(q)
def get_users_with_perms(obj, attach_perms=False, with_superusers=False,
        with_group_users=True):
    """
    Returns queryset of all ``User`` objects with *any* object permissions for
    the given ``obj``.

    :param obj: persisted Django's ``Model`` instance

    :param attach_perms: Default: ``False``. If set to ``True`` result would be
      dictionary of ``User`` instances with permissions' codenames list as
      values. This would fetch users eagerly!

    :param with_superusers: Default: ``False``. If set to ``True`` result would
      contain all superusers.

    :param with_group_users: Default: ``True``. If set to ``False`` result would
      **not** contain those users who have only group permissions for given
      ``obj``.

    Example::

        >>> from django.contrib.flatpages.models import FlatPage
        >>> from django.contrib.auth.models import User
        >>> from guardian.shortcuts import assign_perm, get_users_with_perms
        >>>
        >>> page = FlatPage.objects.create(title='Some page', path='/some/page/')
        >>> joe = User.objects.create_user('joe', '*****@*****.**', 'joesecret')
        >>> assign_perm('change_flatpage', joe, page)
        >>>
        >>> get_users_with_perms(page)
        [<User: joe>]
        >>>
        >>> get_users_with_perms(page, attach_perms=True)
        {<User: joe>: [u'change_flatpage']}

    """
    ctype = ContentType.objects.get_for_model(obj)
    if not attach_perms:
        # It's much easier without attached perms so we do it first if that is
        # the case
        user_model = get_user_obj_perms_model(obj)
        related_name = user_model.user.field.related_query_name()
        if user_model.objects.is_generic():
            user_filters = {
                '%s__content_type' % related_name: ctype,
                '%s__object_pk' % related_name: obj.pk,
            }
        else:
            user_filters = {'%s__content_object' % related_name: obj}
        qset = Q(**user_filters)
        if with_group_users:
            group_model = get_group_obj_perms_model(obj)
            group_rel_name = group_model.group.field.related_query_name()
            if group_model.objects.is_generic():
                group_filters = {
                    'groups__%s__content_type' % group_rel_name: ctype,
                    'groups__%s__object_pk' % group_rel_name: obj.pk,
                }
            else:
                group_filters = {
                    'groups__%s__content_object' % group_rel_name: obj,
                }
            qset = qset | Q(**group_filters)
        if with_superusers:
            qset = qset | Q(is_superuser=True)
        return get_user_model().objects.filter(qset).distinct()
    else:
        # TODO: Do not hit db for each user!
        users = {}
        for user in get_users_with_perms(obj,
                with_group_users=with_group_users):
            users[user] = sorted(get_perms(user, obj))
        return users
Пример #34
0
def get_users_with_perms(obj, attach_perms=False, with_superusers=False,
                         with_group_users=True, only_with_perms_in=None):
    """
    Returns queryset of all ``User`` objects with *any* object permissions for
    the given ``obj``.

    :param obj: persisted Django's ``Model`` instance

    :param attach_perms: Default: ``False``. If set to ``True`` result would be
      dictionary of ``User`` instances with permissions' codenames list as
      values. This would fetch users eagerly!

    :param with_superusers: Default: ``False``. If set to ``True`` result would
      contain all superusers.

    :param with_group_users: Default: ``True``. If set to ``False`` result would
      **not** contain those users who have only group permissions for given
      ``obj``.

    :param only_with_perms_in: Default: ``None``. If set to an iterable of
      permission strings then only users with those permissions would be
      returned.

    Example::

        >>> from django.contrib.flatpages.models import FlatPage
        >>> from django.contrib.auth.models import User
        >>> from guardian.shortcuts import assign_perm, get_users_with_perms
        >>>
        >>> page = FlatPage.objects.create(title='Some page', path='/some/page/')
        >>> joe = User.objects.create_user('joe', '*****@*****.**', 'joesecret')
        >>> dan = User.objects.create_user('dan', '*****@*****.**', 'dansecret')
        >>> assign_perm('change_flatpage', joe, page)
        >>> assign_perm('delete_flatpage', dan, page)
        >>>
        >>> get_users_with_perms(page)
        [<User: joe>, <User: dan>]
        >>>
        >>> get_users_with_perms(page, attach_perms=True)
        {<User: joe>: [u'change_flatpage'], <User: dan>: [u'delete_flatpage']}
        >>> get_users_with_perms(page, only_with_perms_in=['change_flatpage'])
        [<User: joe>]

    """
    ctype = get_content_type(obj)
    if not attach_perms:
        # It's much easier without attached perms so we do it first if that is
        # the case
        user_model = get_user_obj_perms_model(obj)
        related_name = user_model.user.field.related_query_name()
        if user_model.objects.is_generic():
            user_filters = {
                '%s__content_type' % related_name: ctype,
                '%s__object_pk' % related_name: obj.pk,
            }
        else:
            user_filters = {'%s__content_object' % related_name: obj}
        qset = Q(**user_filters)
        if only_with_perms_in is not None:
            permission_ids = Permission.objects.filter(content_type=ctype, codename__in=only_with_perms_in).values_list('id', flat=True)
            qset &= Q(**{
                '%s__permission_id__in' % related_name: permission_ids,
                })
        if with_group_users:
            group_model = get_group_obj_perms_model(obj)
            group_rel_name = group_model.group.field.related_query_name()
            if group_model.objects.is_generic():
                group_filters = {
                    'groups__%s__content_type' % group_rel_name: ctype,
                    'groups__%s__object_pk' % group_rel_name: obj.pk,
                }
            else:
                group_filters = {
                    'groups__%s__content_object' % group_rel_name: obj,
                }
            if only_with_perms_in is not None:
                group_filters.update({
                    'groups__%s__permission_id__in' % group_rel_name: permission_ids,
                    })
            qset = qset | Q(**group_filters)
        if with_superusers:
            qset = qset | Q(is_superuser=True)
        return get_user_model().objects.filter(qset).distinct()
    else:
        # TODO: Do not hit db for each user!
        users = {}
        for user in get_users_with_perms(obj,
                                         with_group_users=with_group_users,
                                         only_with_perms_in=only_with_perms_in,
                                         with_superusers=with_superusers):
            # TODO: Support the case of set with_group_users but not with_superusers.
            if with_group_users or with_superusers:
                users[user] = sorted(get_perms(user, obj))
            else:
                users[user] = sorted(get_user_perms(user, obj))
        return users
def assign_perm(perm, user_or_group, obj=None):
    """
    Assigns permission to user/group and object pair.

    :param perm: proper permission for given ``obj``, as string (in format:
      ``app_label.codename`` or ``codename``). If ``obj`` is not given, must
      be in format ``app_label.codename``.

    :param user_or_group: instance of ``User``, ``AnonymousUser`` or ``Group``;
      passing any other object would raise
      ``guardian.exceptions.NotUserNorGroup`` exception

    :param obj: persisted Django's ``Model`` instance or ``None`` if assigning
      global permission. Default is ``None``.

    We can assign permission for ``Model`` instance for specific user:

    >>> from django.contrib.sites.models import Site
    >>> from guardian.models import User
    >>> from guardian.shortcuts import assign_perm
    >>> site = Site.objects.get_current()
    >>> user = User.objects.create(username='******')
    >>> assign_perm("change_site", user, site)
    <UserObjectPermission: example.com | joe | change_site>
    >>> user.has_perm("change_site", site)
    True

    ... or we can assign permission for group:

    >>> group = Group.objects.create(name='joe-group')
    >>> user.groups.add(group)
    >>> assign_perm("delete_site", group, site)
    <GroupObjectPermission: example.com | joe-group | delete_site>
    >>> user.has_perm("delete_site", site)
    True

    **Global permissions**

    This function may also be used to assign standard, *global* permissions if
    ``obj`` parameter is omitted. Added Permission would be returned in that
    case:

    >>> assign_perm("sites.change_site", user)
    <Permission: sites | site | Can change site>

    """

    user, group = get_identity(user_or_group)
    # If obj is None we try to operate on global permissions
    if obj is None:
        try:
            app_label, codename = perm.split('.', 1)
        except ValueError:
            raise ValueError("For global permissions, first argument must be in"
                " format: 'app_label.codename' (is %r)" % perm)
        perm = Permission.objects.get(content_type__app_label=app_label,
            codename=codename)
        if user:
            user.user_permissions.add(perm)
            return perm
        if group:
            group.permissions.add(perm)
            return perm
    perm = perm.split('.')[-1]
    if user:
        model = get_user_obj_perms_model(obj)
        return model.objects.assign_perm(perm, user, obj)
    if group:
        model = get_group_obj_perms_model(obj)
        return model.objects.assign_perm(perm, group, obj)
Пример #36
0
def get_objects_for_user(user, perms, klass=None, use_groups=True, any_perm=False,
        with_superuser=True):
    """
    Returns queryset of objects for which a given ``user`` has *all*
    permissions present at ``perms``.

    :param user: ``User`` or ``AnonymousUser`` instance for which objects would
      be returned.
    :param perms: single permission string, or sequence of permission strings
      which should be checked.
      If ``klass`` parameter is not given, those should be full permission
      names rather than only codenames (i.e. ``auth.change_user``). If more than
      one permission is present within sequence, their content type **must** be
      the same or ``MixedContentTypeError`` exception would be raised.
    :param klass: may be a Model, Manager or QuerySet object. If not given
      this parameter would be computed based on given ``params``.
    :param use_groups: if ``False``, wouldn't check user's groups object
      permissions. Default is ``True``.
    :param any_perm: if True, any of permission in sequence is accepted
    :param with_superuser: if ``True`` returns the entire queryset if not it will
    only return objects the user has explicit permissions.
    
    :raises MixedContentTypeError: when computed content type for ``perms``
      and/or ``klass`` clashes.
    :raises WrongAppError: if cannot compute app label for given ``perms``/
      ``klass``.

    Example::

        >>> from django.contrib.auth.models import User
        >>> from guardian.shortcuts import get_objects_for_user
        >>> joe = User.objects.get(username='******')
        >>> get_objects_for_user(joe, 'auth.change_group')
        []
        >>> from guardian.shortcuts import assign_perm
        >>> group = Group.objects.create('some group')
        >>> assign_perm('auth.change_group', joe, group)
        >>> get_objects_for_user(joe, 'auth.change_group')
        [<Group some group>]

    The permission string can also be an iterable. Continuing with the previous example:

        >>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'])
        []
        >>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'], any_perm=True)
        [<Group some group>]
        >>> assign_perm('auth.delete_group', joe, group)
        >>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'])
        [<Group some group>]

    """
    if isinstance(perms, basestring):
        perms = [perms]
    ctype = None
    app_label = None
    codenames = set()

    # Compute codenames set and ctype if possible
    for perm in perms:
        if '.' in perm:
            new_app_label, codename = perm.split('.', 1)
            if app_label is not None and app_label != new_app_label:
                raise MixedContentTypeError("Given perms must have same app "
                    "label (%s != %s)" % (app_label, new_app_label))
            else:
                app_label = new_app_label
        else:
            codename = perm
        codenames.add(codename)
        if app_label is not None:
            new_ctype = ContentType.objects.get(app_label=app_label,
                permission__codename=codename)
            if ctype is not None and ctype != new_ctype:
                raise MixedContentTypeError("ContentType was once computed "
                    "to be %s and another one %s" % (ctype, new_ctype))
            else:
                ctype = new_ctype

    # Compute queryset and ctype if still missing
    if ctype is None and klass is None:
        raise WrongAppError("Cannot determine content type")
    elif ctype is None and klass is not None:
        queryset = _get_queryset(klass)
        ctype = ContentType.objects.get_for_model(queryset.model)
    elif ctype is not None and klass is None:
        queryset = _get_queryset(ctype.model_class())
    else:
        queryset = _get_queryset(klass)
        if ctype.model_class() != queryset.model:
            raise MixedContentTypeError("Content type for given perms and "
                "klass differs")

    # At this point, we should have both ctype and queryset and they should
    # match which means: ctype.model_class() == queryset.model
    # we should also have ``codenames`` list

    # First check if user is superuser and if so, return queryset immediately
    if with_superuser and user.is_superuser:
        return queryset

    # Check if the user is anonymous. The
    # django.contrib.auth.models.AnonymousUser object doesn't work for queries
    # and it's nice to be able to pass in request.user blindly.
    if user.is_anonymous():
        user = get_anonymous_user()

    # Now we should extract list of pk values for which we would filter queryset
    user_model = get_user_obj_perms_model(queryset.model)
    user_obj_perms_queryset = (user_model.objects
        .filter(user=user)
        .filter(permission__content_type=ctype)
        .filter(permission__codename__in=codenames))
    if user_model.objects.is_generic():
        fields = ['object_pk', 'permission__codename']
    else:
        fields = ['content_object__pk', 'permission__codename']

    if use_groups:
        group_model = get_group_obj_perms_model(queryset.model)
        group_filters = {
            'permission__content_type': ctype,
            'permission__codename__in': codenames,
            'group__%s' % get_user_model().groups.field.related_query_name(): user,
        }
        groups_obj_perms_queryset = group_model.objects.filter(**group_filters)
        if group_model.objects.is_generic():
            fields = ['object_pk', 'permission__codename']
        else:
            fields = ['content_object__pk', 'permission__codename']
        if not any_perm:
            user_obj_perms = user_obj_perms_queryset.values_list(*fields)
            groups_obj_perms = groups_obj_perms_queryset.values_list(*fields)
            data = list(user_obj_perms) + list(groups_obj_perms)
            keyfunc = lambda t: t[0] # sorting/grouping by pk (first in result tuple)
            data = sorted(data, key=keyfunc)
            pk_list = []
            for pk, group in groupby(data, keyfunc):
                obj_codenames = set((e[1] for e in group))
                if codenames.issubset(obj_codenames):
                    pk_list.append(pk)
            objects = queryset.filter(pk__in=pk_list)
            return objects

    if not any_perm and len(codenames) > 1:
        counts = user_obj_perms_queryset.values(fields[0]).annotate(object_pk_count=Count(fields[0]))
        user_obj_perms_queryset = counts.filter(object_pk_count__gte=len(codenames))

    values = user_obj_perms_queryset.values_list(fields[0], flat=True)
    if user_model.objects.is_generic():
        values = [int(v) for v in values]
    objects = queryset.filter(pk__in=values)
    if use_groups:
        values = groups_obj_perms_queryset.values_list(fields[0], flat=True)
        if group_model.objects.is_generic():
            values = [int(v) for v in values]
        objects |= queryset.filter(pk__in=values)

    return objects
def get_objects_for_group(group, perms, klass=None, any_perm=False, accept_global_perms=True):
    """
    Returns queryset of objects for which a given ``group`` has *all*
    permissions present at ``perms``.

    :param group: ``Group`` instance for which objects would be returned.
    :param perms: single permission string, or sequence of permission strings
      which should be checked.
      If ``klass`` parameter is not given, those should be full permission
      names rather than only codenames (i.e. ``auth.change_user``). If more than
      one permission is present within sequence, their content type **must** be
      the same or ``MixedContentTypeError`` exception would be raised.
    :param klass: may be a Model, Manager or QuerySet object. If not given
      this parameter would be computed based on given ``params``.
    :param any_perm: if True, any of permission in sequence is accepted
    :param accept_global_perms: if ``True`` takes global permissions into account.
      If any_perm is set to false then the intersection of matching objects based on global and object based permissions
      is returned. Default is ``True``.

    :raises MixedContentTypeError: when computed content type for ``perms``
      and/or ``klass`` clashes.
    :raises WrongAppError: if cannot compute app label for given ``perms``/
      ``klass``.

    Example:

    Let's assume we have a ``Task`` model belonging to the ``tasker`` app with
    the default add_task, change_task and delete_task permissions provided
    by Django::

        >>> from guardian.shortcuts import get_objects_for_group
        >>> from tasker import Task
        >>> group = Group.objects.create('some group')
        >>> task = Task.objects.create('some task')
        >>> get_objects_for_group(group, 'tasker.add_task')
        []
        >>> from guardian.shortcuts import assign_perm
        >>> assign_perm('tasker.add_task', group, task)
        >>> get_objects_for_group(group, 'tasker.add_task')
        [<Task some task>]

    The permission string can also be an iterable. Continuing with the previous example:
        >>> get_objects_for_group(group, ['tasker.add_task', 'tasker.delete_task'])
        []
        >>> assign_perm('tasker.delete_task', group, task)
        >>> get_objects_for_group(group, ['tasker.add_task', 'tasker.delete_task'])
        [<Task some task>]

    Global permissions assigned to the group are also taken into account. Continuing with previous example:
        >>> task_other = Task.objects.create('other task')
        >>> assign_perm('tasker.change_task', group)
        >>> get_objects_for_group(group, ['tasker.change_task'])
        [<Task some task>, <Task other task>]
        >>> get_objects_for_group(group, ['tasker.change_task'], accept_global_perms=False)
        [<Task some task>]

    """
    if isinstance(perms, basestring):
        perms = [perms]
    ctype = None
    app_label = None
    codenames = set()

    # Compute codenames set and ctype if possible
    for perm in perms:
        if '.' in perm:
            new_app_label, codename = perm.split('.', 1)
            if app_label is not None and app_label != new_app_label:
                raise MixedContentTypeError("Given perms must have same app "
                    "label (%s != %s)" % (app_label, new_app_label))
            else:
                app_label = new_app_label
        else:
            codename = perm
        codenames.add(codename)
        if app_label is not None:
            new_ctype = ContentType.objects.get(app_label=app_label,
                permission__codename=codename)
            if ctype is not None and ctype != new_ctype:
                raise MixedContentTypeError("ContentType was once computed "
                    "to be %s and another one %s" % (ctype, new_ctype))
            else:
                ctype = new_ctype

    # Compute queryset and ctype if still missing
    if ctype is None and klass is None:
        raise WrongAppError("Cannot determine content type")
    elif ctype is None and klass is not None:
        queryset = _get_queryset(klass)
        ctype = ContentType.objects.get_for_model(queryset.model)
    elif ctype is not None and klass is None:
        queryset = _get_queryset(ctype.model_class())
    else:
        queryset = _get_queryset(klass)
        if ctype.model_class() != queryset.model:
            raise MixedContentTypeError("Content type for given perms and "
                "klass differs")

    # At this point, we should have both ctype and queryset and they should
    # match which means: ctype.model_class() == queryset.model
    # we should also have ``codenames`` list

    global_perms = set()
    if accept_global_perms:
        global_perm_set = group.permissions.values_list('codename', flat=True)
        for code in codenames:
            if code in global_perm_set:
                global_perms.add(code)
        for code in global_perms:
            codenames.remove(code)
        if len(global_perms) > 0 and (len(codenames) == 0 or any_perm):
            return queryset

    # Now we should extract list of pk values for which we would filter queryset
    group_model = get_group_obj_perms_model(queryset.model)
    groups_obj_perms_queryset = (group_model.objects
        .filter(group=group)
        .filter(permission__content_type=ctype)
        .filter(permission__codename__in=codenames))
    if group_model.objects.is_generic():
        fields = ['object_pk', 'permission__codename']
    else:
        fields = ['content_object__pk', 'permission__codename']
    groups_obj_perms = groups_obj_perms_queryset.values_list(*fields)
    data = list(groups_obj_perms)

    keyfunc = lambda t: t[0] # sorting/grouping by pk (first in result tuple)
    data = sorted(data, key=keyfunc)
    pk_list = []
    for pk, group in groupby(data, keyfunc):
        obj_codenames = set((e[1] for e in group))
        if any_perm or codenames.issubset(obj_codenames):
            pk_list.append(pk)
    objects = queryset.filter(pk__in=pk_list)
    return objects
Пример #38
0
 def test_group_model(self):
     # this test assumes that there were no direct obj perms model to Group
     # model defined (i.e. while testing guardian app in some custom project)
     self.assertEqual(get_group_obj_perms_model(Group),
         GroupObjectPermission)
Пример #39
0
def get_objects_for_user(user, perms, klass=None, use_groups=True, any_perm=False,
                         with_superuser=True, accept_global_perms=True, perms_filter='pk__in'):
    """Return queryset with required permissions."""
    if isinstance(perms, six.string_types):
        perms = [perms]

    ctype = None
    app_label = None
    codenames = set()

    # Compute codenames set and ctype if possible
    for perm in perms:
        if '.' in perm:
            new_app_label, codename = perm.split('.', 1)
            if app_label is not None and app_label != new_app_label:
                raise MixedContentTypeError(
                    "Given perms must have same app label "
                    "({} != {})".format(app_label, new_app_label))
            else:
                app_label = new_app_label
        else:
            codename = perm
        codenames.add(codename)

        if app_label is not None:
            new_ctype = ContentType.objects.get(app_label=app_label,
                                                permission__codename=codename)
            if ctype is not None and ctype != new_ctype:
                raise MixedContentTypeError(
                    "ContentType was once computed to be {} and another "
                    "one {}".format(ctype, new_ctype))
            else:
                ctype = new_ctype

    # Compute queryset and ctype if still missing
    if ctype is None and klass is not None:
        queryset = _get_queryset(klass)
        ctype = ContentType.objects.get_for_model(queryset.model)
    elif ctype is not None and klass is None:
        queryset = _get_queryset(ctype.model_class())
    elif klass is None:
        raise WrongAppError("Cannot determine content type")
    else:
        queryset = _get_queryset(klass)
        if ctype.model_class() != queryset.model and perms_filter == 'pk__in':
            raise MixedContentTypeError("Content type for given perms and "
                                        "klass differs")

    # At this point, we should have both ctype and queryset and they should
    # match which means: ctype.model_class() == queryset.model
    # we should also have `codenames` list

    # First check if user is superuser and if so, return queryset immediately
    if with_superuser and user.is_superuser:
        return queryset

    # Check if the user is anonymous. The
    # django.contrib.auth.models.AnonymousUser object doesn't work for queries
    # and it's nice to be able to pass in request.user blindly.
    if user.is_anonymous():
        user = get_anonymous_user()

    global_perms = set()
    has_global_perms = False
    # a superuser has by default assigned global perms for any
    if accept_global_perms and with_superuser:
        for code in codenames:
            if user.has_perm(ctype.app_label + '.' + code):
                global_perms.add(code)
        for code in global_perms:
            codenames.remove(code)
        # prerequisite: there must be elements in global_perms otherwise just
        # follow the procedure for object based permissions only AND
        # 1. codenames is empty, which means that permissions are ONLY set
        # globally, therefore return the full queryset.
        # OR
        # 2. any_perm is True, then the global permission beats the object
        # based permission anyway, therefore return full queryset
        if len(global_perms) > 0 and (len(codenames) == 0 or any_perm):
            return queryset
        # if we have global perms and still some object based perms differing
        # from global perms and any_perm is set to false, then we have to flag
        # that global perms exist in order to merge object based permissions by
        # user and by group correctly. Scenario: global perm change_xx and
        # object based perm delete_xx on object A for user, and object based
        # permission delete_xx  on object B for group, to which user is
        # assigned.
        # get_objects_for_user(user, [change_xx, delete_xx], use_groups=True,
        # any_perm=False, accept_global_perms=True) must retrieve object A and
        # B.
        elif len(global_perms) > 0 and (len(codenames) > 0):
            has_global_perms = True

    # Now we should extract list of pk values for which we would filter
    # queryset
    user_model = get_user_obj_perms_model(queryset.model)
    user_obj_perms_queryset = (user_model.objects
                               .filter(user=user)
                               .filter(permission__content_type=ctype))

    if len(codenames):
        user_obj_perms_queryset = user_obj_perms_queryset.filter(
            permission__codename__in=codenames)
    direct_fields = ['content_object__pk', 'permission__codename']
    generic_fields = ['object_pk', 'permission__codename']
    if user_model.objects.is_generic():
        user_fields = generic_fields
    else:
        user_fields = direct_fields

    if use_groups:
        group_model = get_group_obj_perms_model(queryset.model)
        group_filters = {
            'permission__content_type': ctype,
            'group__{}'.format(get_user_model().groups.field.related_query_name()): user,  # pylint: disable=no-member
        }
        if len(codenames):
            group_filters.update({
                'permission__codename__in': codenames,
            })
        groups_obj_perms_queryset = group_model.objects.filter(**group_filters)
        if group_model.objects.is_generic():
            group_fields = generic_fields
        else:
            group_fields = direct_fields
        if not any_perm and len(codenames) and not has_global_perms:
            user_obj_perms = user_obj_perms_queryset.values_list(*user_fields)
            groups_obj_perms = groups_obj_perms_queryset.values_list(*group_fields)
            data = list(user_obj_perms) + list(groups_obj_perms)
            # sorting/grouping by pk (first in result tuple)
            data = sorted(data, key=lambda t: t[0])
            pk_list = []
            for pk, group in groupby(data, lambda t: t[0]):
                obj_codenames = set((e[1] for e in group))
                if codenames.issubset(obj_codenames):
                    pk_list.append(pk)
            objects = queryset.filter(**{perms_filter: pk_list})
            return objects

    if not any_perm and len(codenames) > 1:
        counts = user_obj_perms_queryset.values(
            user_fields[0]).annotate(object_pk_count=Count(user_fields[0]))
        user_obj_perms_queryset = counts.filter(
            object_pk_count__gte=len(codenames))

    values = user_obj_perms_queryset.values_list(user_fields[0], flat=True)
    if user_model.objects.is_generic():
        values = list(values)
    query = Q(**{perms_filter: values})
    if use_groups:
        values = groups_obj_perms_queryset.values_list(group_fields[0], flat=True)
        if group_model.objects.is_generic():
            values = list(values)
        query |= Q(**{perms_filter: values})

    return queryset.filter(query)
Пример #40
0
    def get_perms(self, obj):
        """
        Returns list of ``codename``'s of all permissions for given ``obj``.

        :param obj: Django model instance for which permission should be checked

        """
        if self.user and not self.user.is_active:
            return []
        User = get_user_model()
        ctype = ContentType.objects.get_for_model(obj)
        key = self.get_local_cache_key(obj)
        if not key in self._obj_perms_cache:

            group_model = get_group_obj_perms_model(obj)
            group_rel_name = group_model.permission.field.related_query_name()
            if self.user:
                fieldname = '%s__group__%s' % (
                    group_rel_name,
                    User.groups.field.related_query_name(),
                )
                group_filters = {fieldname: self.user}
            else:
                group_filters = {'%s__group' % group_rel_name: self.group}
            if group_model.objects.is_generic():
                group_filters.update({
                    '%s__content_type' % group_rel_name: ctype,
                    '%s__object_pk' % group_rel_name: obj.pk,
                })
            else:
                group_filters['%s__content_object' % group_rel_name] = obj

            if self.user and self.user.is_superuser:
                perms = list(chain(*Permission.objects
                    .filter(content_type=ctype)
                    .values_list("codename")))
            elif self.user:
                model = get_user_obj_perms_model(obj)
                related_name = model.permission.field.related_query_name()
                user_filters = {'%s__user' % related_name: self.user}
                if model.objects.is_generic():
                    user_filters.update({
                        '%s__content_type' % related_name: ctype,
                        '%s__object_pk' % related_name: obj.pk,
                    })
                else:
                    user_filters['%s__content_object' % related_name] = obj
                perms_qs = Permission.objects.filter(content_type=ctype)
                # Query user and group permissions separately and then combine
                # the results to avoid a slow query
                user_perms_qs = perms_qs.filter(**user_filters)
                user_perms = user_perms_qs.values_list("codename", flat=True)
                group_perms_qs = perms_qs.filter(**group_filters)
                group_perms = group_perms_qs.values_list("codename", flat=True)
                perms = list(set(chain(user_perms, group_perms)))
            else:
                perms = list(set(chain(*Permission.objects
                    .filter(content_type=ctype)
                    .filter(**group_filters)
                    .values_list("codename"))))
            self._obj_perms_cache[key] = perms
        return self._obj_perms_cache[key]
Пример #41
0
def get_unattached_users_with_perms_qset(obj,
                                         perm,
                                         permission_expiry=False,
                                         with_group_users=True,
                                         with_superusers=False,
                                         only_with_perms_in=None):
    # It's much easier without attached perms so we do it first if that is
    # the case

    # JOINing into the perms table is a no-go - would have to be done three times, for users, groups and orgs.
    # Getting perm id first allows us to forgo this JOIN
    perm_id = None
    if perm:
        perm_id = cache.get("permission_id_{0}".format(perm))
        if not perm_id:
            perm_id = Permission.objects.get(codename=perm).id
            cache.set("permission_id_{0}".format(perm), perm_id, 86400)
    ctype = get_content_type(obj)
    user_model = get_user_obj_perms_model(obj)
    related_name = user_model.user.field.related_query_name()
    if user_model.objects.is_generic():
        user_filters = {
            '%s__content_type' % related_name: ctype,
            '%s__object_pk' % related_name: obj.pk,
        }
        if perm_id:
            user_filters.update({
                '%s__permission_id' % related_name: perm_id,
            })
    else:
        user_filters = {'%s__content_object' % related_name: obj}
    qset = Q(**user_filters)
    if only_with_perms_in is not None:
        permission_ids = Permission.objects.filter(
            content_type=ctype,
            codename__in=only_with_perms_in).values_list('id', flat=True)
        qset &= Q(**{
            '%s__permission_id__in' % related_name: permission_ids,
        })

    if permission_expiry:
        kwargs1 = {"%s__permission_expiry" % related_name: None}
        kwargs2 = {
            "%s__permission_expiry__gte" % related_name:
            datetime.utcnow().replace(tzinfo=utc)
        }
        qset &= (Q(**kwargs1) | Q(**kwargs2))

    if with_group_users:
        group_model = get_group_obj_perms_model(obj)
        group_rel_name = group_model.group.field.related_query_name()
        if group_model.objects.is_generic():
            group_filters = {
                'groups__%s__content_type' % group_rel_name: ctype,
                'groups__%s__object_pk' % group_rel_name: obj.pk,
            }
            if perm_id:
                group_filters.update({
                    'groups__%s__permission_id' % group_rel_name:
                    perm_id,
                })
        else:
            group_filters = {
                'groups__%s__content_object' % group_rel_name: obj,
            }
        if only_with_perms_in is not None:
            permission_ids = Permission.objects.filter(
                content_type=ctype,
                codename__in=only_with_perms_in).values_list('id', flat=True)
            group_filters.update({
                'groups__%s__permission_id__in' % group_rel_name:
                permission_ids,
            })
        qset = qset | Q(**group_filters)

        org_model = get_organization_obj_perms_model(obj)
        organization_rel_name = org_model.organization.field.related_query_name(
        )
        if org_model.objects.is_generic():
            organization_filters = {
                'organizations_organization__%s__content_type' % organization_rel_name:
                ctype,
                'organizations_organization__%s__object_pk' % organization_rel_name:
                obj.pk,
            }
            if perm_id:
                organization_filters.update({
                    'organizations_organization__%s__permission_id' % organization_rel_name:
                    perm_id,
                })
        else:
            organization_filters = {
                'organizations_organization__%s__content_object' % organization_rel_name:
                obj
            }

        if permission_expiry:
            kwargs1 = {
                "organizations_organization__%s__permission_expiry" % organization_rel_name:
                None
            }
            kwargs2 = {
                "organizations_organization__%s__permission_expiry__gte" % organization_rel_name:
                datetime.utcnow().replace(tzinfo=utc)
            }
            qset &= (Q(**kwargs1) | Q(**kwargs2))

        qset = qset | Q(**organization_filters)
    if with_superusers:
        qset = qset | Q(is_superuser=True)
    return qset
Пример #42
0
    def prefetch_perms(self, objects):
        """
        Prefetches the permissions for objects in ``objects`` and puts them in the cache.

        :param objects: Iterable of Django model objects

        """
        if self.user and not self.user.is_active:
            return []

        User = get_user_model()
        pks, model, ctype = _get_pks_model_and_ctype(objects)

        if self.user and self.user.is_superuser:
            perms = list(
                chain(*Permission.objects.filter(
                    content_type=ctype).values_list("codename")))

            for pk in pks:
                key = (ctype.id, force_text(pk))
                self._obj_perms_cache[key] = perms

            return True

        group_model = get_group_obj_perms_model(model)

        if self.user:
            fieldname = 'group__%s' % (
                User.groups.field.related_query_name(), )
            group_filters = {fieldname: self.user}
        else:
            group_filters = {'group': self.group}

        if group_model.objects.is_generic():
            group_filters.update({
                'content_type': ctype,
                'object_pk__in': pks,
            })
        else:
            group_filters.update({'content_object_id__in': pks})

        if self.user:
            model = get_user_obj_perms_model(model)
            user_filters = {
                'user': self.user,
            }

            if model.objects.is_generic():
                user_filters.update({
                    'content_type': ctype,
                    'object_pk__in': pks
                })
            else:
                user_filters.update({'content_object_id__in': pks})

            # Query user and group permissions separately and then combine
            # the results to avoid a slow query
            user_perms_qs = model.objects.filter(
                **user_filters).select_related('permission')
            group_perms_qs = group_model.objects.filter(
                **group_filters).select_related('permission')
            perms = chain(user_perms_qs, group_perms_qs)
        else:
            perms = chain(*(group_model.objects.filter(
                **group_filters).select_related('permission'), ))

        # initialize entry in '_obj_perms_cache' for all prefetched objects
        for obj in objects:
            key = self.get_local_cache_key(obj)
            if key not in self._obj_perms_cache:
                self._obj_perms_cache[key] = []

        for perm in perms:
            if type(perm).objects.is_generic():
                key = (ctype.id, perm.object_pk)
            else:
                key = (ctype.id, force_text(perm.content_object_id))

            self._obj_perms_cache[key].append(perm.permission.codename)

        return True
def get_objects_for_user(user,
                         perms,
                         klass=None,
                         use_groups=True,
                         any_perm=False,
                         with_superuser=True):
    """
    Returns queryset of objects for which a given ``user`` has *all*
    permissions present at ``perms``.

    :param user: ``User`` or ``AnonymousUser`` instance for which objects would
      be returned.
    :param perms: single permission string, or sequence of permission strings
      which should be checked.
      If ``klass`` parameter is not given, those should be full permission
      names rather than only codenames (i.e. ``auth.change_user``). If more than
      one permission is present within sequence, their content type **must** be
      the same or ``MixedContentTypeError`` exception would be raised.
    :param klass: may be a Model, Manager or QuerySet object. If not given
      this parameter would be computed based on given ``params``.
    :param use_groups: if ``False``, wouldn't check user's groups object
      permissions. Default is ``True``.
    :param any_perm: if True, any of permission in sequence is accepted
    :param with_superuser: if ``True`` returns the entire queryset if not it will
    only return objects the user has explicit permissions.

    :raises MixedContentTypeError: when computed content type for ``perms``
      and/or ``klass`` clashes.
    :raises WrongAppError: if cannot compute app label for given ``perms``/
      ``klass``.

    Example::

        >>> from django.contrib.auth.models import User
        >>> from guardian.shortcuts import get_objects_for_user
        >>> joe = User.objects.get(username='******')
        >>> get_objects_for_user(joe, 'auth.change_group')
        []
        >>> from guardian.shortcuts import assign_perm
        >>> group = Group.objects.create('some group')
        >>> assign_perm('auth.change_group', joe, group)
        >>> get_objects_for_user(joe, 'auth.change_group')
        [<Group some group>]

    The permission string can also be an iterable. Continuing with the previous example:

        >>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'])
        []
        >>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'], any_perm=True)
        [<Group some group>]
        >>> assign_perm('auth.delete_group', joe, group)
        >>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'])
        [<Group some group>]

    """
    if isinstance(perms, str):
        perms = [perms]
    ctype = None
    app_label = None
    codenames = set()

    # Compute codenames set and ctype if possible
    for perm in perms:
        if '.' in perm:
            new_app_label, codename = perm.split('.', 1)
            if app_label is not None and app_label != new_app_label:
                raise MixedContentTypeError("Given perms must have same app "
                                            "label (%s != %s)" %
                                            (app_label, new_app_label))
            else:
                app_label = new_app_label
        else:
            codename = perm
        codenames.add(codename)
        if app_label is not None:
            new_ctype = ContentType.objects.get(app_label=app_label,
                                                permission__codename=codename)
            if ctype is not None and ctype != new_ctype:
                raise MixedContentTypeError("ContentType was once computed "
                                            "to be %s and another one %s" %
                                            (ctype, new_ctype))
            else:
                ctype = new_ctype

    # Compute queryset and ctype if still missing
    if ctype is None and klass is None:
        raise WrongAppError("Cannot determine content type")
    elif ctype is None and klass is not None:
        queryset = _get_queryset(klass)
        ctype = ContentType.objects.get_for_model(queryset.model)
    elif ctype is not None and klass is None:
        queryset = _get_queryset(ctype.model_class())
    else:
        queryset = _get_queryset(klass)
        if ctype.model_class() != queryset.model:
            raise MixedContentTypeError("Content type for given perms and "
                                        "klass differs")

    # At this point, we should have both ctype and queryset and they should
    # match which means: ctype.model_class() == queryset.model
    # we should also have ``codenames`` list

    # First check if user is superuser and if so, return queryset immediately
    if with_superuser and user.is_superuser:
        return queryset

    # Check if the user is anonymous. The
    # django.contrib.auth.models.AnonymousUser object doesn't work for queries
    # and it's nice to be able to pass in request.user blindly.
    if user.is_anonymous():
        user = get_anonymous_user()

    # Now we should extract list of pk values for which we would filter queryset
    user_model = get_user_obj_perms_model(queryset.model)
    user_obj_perms_queryset = (user_model.objects.filter(user=user).filter(
        permission__content_type=ctype).filter(
            permission__codename__in=codenames))
    if user_model.objects.is_generic():
        fields = ['object_pk', 'permission__codename']
    else:
        fields = ['content_object__pk', 'permission__codename']

    if use_groups:
        group_model = get_group_obj_perms_model(queryset.model)
        group_filters = {
            'permission__content_type': ctype,
            'permission__codename__in': codenames,
            'group__%s' % get_user_model().groups.field.related_query_name():
            user,
        }
        groups_obj_perms_queryset = group_model.objects.filter(**group_filters)
        if group_model.objects.is_generic():
            fields = ['object_pk', 'permission__codename']
        else:
            fields = ['content_object__pk', 'permission__codename']
        if not any_perm:
            user_obj_perms = user_obj_perms_queryset.values_list(*fields)
            groups_obj_perms = groups_obj_perms_queryset.values_list(*fields)
            data = list(user_obj_perms) + list(groups_obj_perms)
            keyfunc = lambda t: t[
                0]  # sorting/grouping by pk (first in result tuple)
            data = sorted(data, key=keyfunc)
            pk_list = []
            for pk, group in groupby(data, keyfunc):
                obj_codenames = set((e[1] for e in group))
                if codenames.issubset(obj_codenames):
                    pk_list.append(pk)
            objects = queryset.filter(pk__in=pk_list)
            return objects

    if not any_perm and len(codenames) > 1:
        counts = user_obj_perms_queryset.values(
            fields[0]).annotate(object_pk_count=Count(fields[0]))
        user_obj_perms_queryset = counts.filter(
            object_pk_count__gte=len(codenames))

    values = user_obj_perms_queryset.values_list(fields[0], flat=True)
    if user_model.objects.is_generic():
        values = list(values)
    objects = queryset.filter(pk__in=values)
    if use_groups:
        values = groups_obj_perms_queryset.values_list(fields[0], flat=True)
        if group_model.objects.is_generic():
            values = list(values)
        objects |= queryset.filter(pk__in=values)

    return objects
Пример #44
0
 def test_group_model(self):
     # this test assumes that there were no direct obj perms model to Group
     # model defined (i.e. while testing guardian app in some custom
     # project)
     self.assertEqual(get_group_obj_perms_model(Group),
                      GroupObjectPermission)
Пример #45
0
def get_users_with_perms(obj,
                         attach_perms=False,
                         with_superusers=False,
                         with_group_users=True):
    """
    Returns queryset of all ``User`` objects with *any* object permissions for
    the given ``obj``.

    :param obj: persisted Django's ``Model`` instance

    :param attach_perms: Default: ``False``. If set to ``True`` result would be
      dictionary of ``User`` instances with permissions' codenames list as
      values. This would fetch users eagerly!

    :param with_superusers: Default: ``False``. If set to ``True`` result would
      contain all superusers.

    :param with_group_users: Default: ``True``. If set to ``False`` result would
      **not** contain those users who have only group permissions for given
      ``obj``.

    Example::

        >>> from django.contrib.flatpages.models import FlatPage
        >>> from django.contrib.auth.models import User
        >>> from guardian.shortcuts import assign_perm, get_users_with_perms
        >>>
        >>> page = FlatPage.objects.create(title='Some page', path='/some/page/')
        >>> joe = User.objects.create_user('joe', '*****@*****.**', 'joesecret')
        >>> assign_perm('change_flatpage', joe, page)
        >>>
        >>> get_users_with_perms(page)
        [<User: joe>]
        >>>
        >>> get_users_with_perms(page, attach_perms=True)
        {<User: joe>: [u'change_flatpage']}

    """
    ctype = get_content_type(obj)
    if not attach_perms:
        # It's much easier without attached perms so we do it first if that is
        # the case
        user_model = get_user_obj_perms_model(obj)
        related_name = user_model.user.field.related_query_name()
        if user_model.objects.is_generic():
            user_filters = {
                '%s__content_type' % related_name: ctype,
                '%s__object_pk' % related_name: obj.pk,
            }
        else:
            user_filters = {'%s__content_object' % related_name: obj}
        qset = Q(**user_filters)
        if with_group_users:
            group_model = get_group_obj_perms_model(obj)
            group_rel_name = group_model.group.field.related_query_name()
            if group_model.objects.is_generic():
                group_filters = {
                    'groups__%s__content_type' % group_rel_name: ctype,
                    'groups__%s__object_pk' % group_rel_name: obj.pk,
                }
            else:
                group_filters = {
                    'groups__%s__content_object' % group_rel_name: obj,
                }
            qset = qset | Q(**group_filters)
        if with_superusers:
            qset = qset | Q(is_superuser=True)
        return get_user_model().objects.filter(qset).distinct()
    else:
        # TODO: Do not hit db for each user!
        users = {}
        for user in get_users_with_perms(obj,
                                         with_group_users=with_group_users,
                                         with_superusers=with_superusers):
            # TODO: Support the case of set with_group_users but not with_superusers.
            if with_group_users or with_superusers:
                users[user] = sorted(get_perms(user, obj))
            else:
                users[user] = sorted(get_user_perms(user, obj))
        return users
Пример #46
0
def get_unattached_users_with_perms_qset(obj, perm, permission_expiry=False, with_group_users=True, with_superusers=False):
    # It's much easier without attached perms so we do it first if that is
    # the case

    # JOINing into the perms table is a no-go - would have to be done three times, for users, groups and orgs.
    # Getting perm id first allows us to forgo this JOIN
    perm_id = None
    if perm:
        perm_id = cache.get("permission_id_{0}".format(perm))
        if not perm_id:
            perm_id = Permission.objects.get(codename=perm).id
            cache.set("permission_id_{0}".format(perm), perm_id, 86400)
    ctype = get_content_type(obj)
    user_model = get_user_obj_perms_model(obj)
    related_name = user_model.user.field.related_query_name()
    if user_model.objects.is_generic():
        user_filters = {
            '%s__content_type' % related_name: ctype,
            '%s__object_pk' % related_name: obj.pk,
        }
        if perm_id:
            user_filters.update({
                '%s__permission_id' % related_name: perm_id,
            })
    else:
        user_filters = {'%s__content_object' % related_name: obj}
    qset = Q(**user_filters)

    if permission_expiry:
        kwargs1 = {"%s__permission_expiry" % related_name: None}
        kwargs2 = {"%s__permission_expiry__gte" % related_name: datetime.utcnow().replace(tzinfo=utc)}
        qset &= (Q(**kwargs1) | Q(**kwargs2))

    if with_group_users:
        group_model = get_group_obj_perms_model(obj)
        group_rel_name = group_model.group.field.related_query_name()
        if group_model.objects.is_generic():
            group_filters = {
                'groups__%s__content_type' % group_rel_name: ctype,
                'groups__%s__object_pk' % group_rel_name: obj.pk,
            }
            if perm_id:
                group_filters.update({
                    'groups__%s__permission_id' % group_rel_name: perm_id,
                })
        else:
            group_filters = {
                'groups__%s__content_object' % group_rel_name: obj,
            }
        qset = qset | Q(**group_filters)

        org_model = get_organization_obj_perms_model(obj)
        organization_rel_name = org_model.organization.field.related_query_name()
        if org_model.objects.is_generic():
            organization_filters = {
                'organizations_organization__%s__content_type' % organization_rel_name: ctype,
                'organizations_organization__%s__object_pk' % organization_rel_name: obj.pk,
            }
            if perm_id:
                organization_filters.update({
                    'organizations_organization__%s__permission_id' % organization_rel_name: perm_id,
                })
        else:
            organization_filters = {
                'organizations_organization__%s__content_object' % organization_rel_name: obj
            }

        if permission_expiry:
            kwargs1 = {"organizations_organization__%s__permission_expiry" % organization_rel_name: None}
            kwargs2 = {"organizations_organization__%s__permission_expiry__gte" % organization_rel_name: datetime.utcnow().replace(tzinfo=utc)}
            qset &= (Q(**kwargs1) | Q(**kwargs2))

        qset = qset | Q(**organization_filters)
    if with_superusers:
        qset = qset | Q(is_superuser=True)
    return qset
Пример #47
0
def get_objects_for_group(group,
                          perms,
                          klass=None,
                          any_perm=False,
                          accept_global_perms=True):
    """
    Returns queryset of objects for which a given ``group`` has *all*
    permissions present at ``perms``.

    :param group: ``Group`` instance for which objects would be returned.
    :param perms: single permission string, or sequence of permission strings
      which should be checked.
      If ``klass`` parameter is not given, those should be full permission
      names rather than only codenames (i.e. ``auth.change_user``). If more than
      one permission is present within sequence, their content type **must** be
      the same or ``MixedContentTypeError`` exception would be raised.
    :param klass: may be a Model, Manager or QuerySet object. If not given
      this parameter would be computed based on given ``params``.
    :param any_perm: if True, any of permission in sequence is accepted
    :param accept_global_perms: if ``True`` takes global permissions into account.
      If any_perm is set to false then the intersection of matching objects based on global and object based permissions
      is returned. Default is ``True``.

    :raises MixedContentTypeError: when computed content type for ``perms``
      and/or ``klass`` clashes.
    :raises WrongAppError: if cannot compute app label for given ``perms``/
      ``klass``.

    Example:

    Let's assume we have a ``Task`` model belonging to the ``tasker`` app with
    the default add_task, change_task and delete_task permissions provided
    by Django::

        >>> from guardian.shortcuts import get_objects_for_group
        >>> from tasker import Task
        >>> group = Group.objects.create('some group')
        >>> task = Task.objects.create('some task')
        >>> get_objects_for_group(group, 'tasker.add_task')
        []
        >>> from guardian.shortcuts import assign_perm
        >>> assign_perm('tasker.add_task', group, task)
        >>> get_objects_for_group(group, 'tasker.add_task')
        [<Task some task>]

    The permission string can also be an iterable. Continuing with the previous example:
        >>> get_objects_for_group(group, ['tasker.add_task', 'tasker.delete_task'])
        []
        >>> assign_perm('tasker.delete_task', group, task)
        >>> get_objects_for_group(group, ['tasker.add_task', 'tasker.delete_task'])
        [<Task some task>]

    Global permissions assigned to the group are also taken into account. Continuing with previous example:
        >>> task_other = Task.objects.create('other task')
        >>> assign_perm('tasker.change_task', group)
        >>> get_objects_for_group(group, ['tasker.change_task'])
        [<Task some task>, <Task other task>]
        >>> get_objects_for_group(group, ['tasker.change_task'], accept_global_perms=False)
        [<Task some task>]

    """
    if isinstance(perms, basestring):
        perms = [perms]
    ctype = None
    app_label = None
    codenames = set()

    # Compute codenames set and ctype if possible
    for perm in perms:
        if '.' in perm:
            new_app_label, codename = perm.split('.', 1)
            if app_label is not None and app_label != new_app_label:
                raise MixedContentTypeError("Given perms must have same app "
                                            "label (%s != %s)" %
                                            (app_label, new_app_label))
            else:
                app_label = new_app_label
        else:
            codename = perm
        codenames.add(codename)
        if app_label is not None:
            new_ctype = ContentType.objects.get(app_label=app_label,
                                                permission__codename=codename)
            if ctype is not None and ctype != new_ctype:
                raise MixedContentTypeError("ContentType was once computed "
                                            "to be %s and another one %s" %
                                            (ctype, new_ctype))
            else:
                ctype = new_ctype

    # Compute queryset and ctype if still missing
    if ctype is None and klass is not None:
        queryset = _get_queryset(klass)
        ctype = get_content_type(queryset.model)
    elif ctype is not None and klass is None:
        queryset = _get_queryset(ctype.model_class())
    elif klass is None:
        raise WrongAppError("Cannot determine content type")
    else:
        queryset = _get_queryset(klass)
        if ctype.model_class() != queryset.model:
            raise MixedContentTypeError("Content type for given perms and "
                                        "klass differs")

    # At this point, we should have both ctype and queryset and they should
    # match which means: ctype.model_class() == queryset.model
    # we should also have ``codenames`` list

    global_perms = set()
    if accept_global_perms:
        global_perm_set = group.permissions.values_list('codename', flat=True)
        for code in codenames:
            if code in global_perm_set:
                global_perms.add(code)
        for code in global_perms:
            codenames.remove(code)
        if len(global_perms) > 0 and (len(codenames) == 0 or any_perm):
            return queryset

    # Now we should extract list of pk values for which we would filter
    # queryset
    group_model = get_group_obj_perms_model(queryset.model)
    groups_obj_perms_queryset = (group_model.objects.filter(
        group=group).filter(permission__content_type=ctype))
    if len(codenames):
        groups_obj_perms_queryset = groups_obj_perms_queryset.filter(
            permission__codename__in=codenames)
    if group_model.objects.is_generic():
        fields = ['object_pk', 'permission__codename']
    else:
        fields = ['content_object__pk', 'permission__codename']
    if not any_perm and len(codenames):
        groups_obj_perms = groups_obj_perms_queryset.values_list(*fields)
        data = list(groups_obj_perms)

        keyfunc = lambda t: t[
            0]  # sorting/grouping by pk (first in result tuple)
        data = sorted(data, key=keyfunc)
        pk_list = []
        for pk, group in groupby(data, keyfunc):
            obj_codenames = set((e[1] for e in group))
            if any_perm or codenames.issubset(obj_codenames):
                pk_list.append(pk)
        objects = queryset.filter(pk__in=pk_list)
        return objects

    values = groups_obj_perms_queryset.values_list(fields[0], flat=True)
    if group_model.objects.is_generic():
        values = list(values)
    return queryset.filter(pk__in=values)
Пример #48
0
def get_users_with_perms(obj, attach_perms=False, with_superusers=False,
        with_group_users=True):
    """
    Returns queryset of all ``User`` objects with *any* object permissions for
    the given ``obj``.

    :param obj: persisted Django's ``Model`` instance

    :param attach_perms: Default: ``False``. If set to ``True`` result would be
      dictionary of ``User`` instances with permissions' codenames list as
      values. This would fetch users eagerly!

    :param with_superusers: Default: ``False``. If set to ``True`` result would
      contain all superusers.

    :param with_group_users: Default: ``True``. If set to ``False`` result would
      **not** contain those users who have only group permissions for given
      ``obj``.

    Example::

        >>> from django.contrib.flatpages.models import FlatPage
        >>> from django.contrib.auth.models import User
        >>> from guardian.shortcuts import assign_perm, get_users_with_perms
        >>>
        >>> page = FlatPage.objects.create(title='Some page', path='/some/page/')
        >>> joe = User.objects.create_user('joe', '*****@*****.**', 'joesecret')
        >>> assign_perm('change_flatpage', joe, page)
        >>>
        >>> get_users_with_perms(page)
        [<User: joe>]
        >>>
        >>> get_users_with_perms(page, attach_perms=True)
        {<User: joe>: [u'change_flatpage']}

    """
    ctype = ContentType.objects.get_for_model(obj)
    if not attach_perms:
        # It's much easier without attached perms so we do it first if that is
        # the case
        user_model = get_user_obj_perms_model(obj)
        related_name = user_model.user.field.related_query_name()
        if user_model.objects.is_generic():
            user_filters = {
                '%s__content_type' % related_name: ctype,
                '%s__object_pk' % related_name: obj.pk,
            }
        else:
            user_filters = {'%s__content_object' % related_name: obj}
        qset = Q(**user_filters)
        if with_group_users:
            group_model = get_group_obj_perms_model(obj)
            group_rel_name = group_model.group.field.related_query_name()
            if group_model.objects.is_generic():
                group_filters = {
                    'groups__%s__content_type' % group_rel_name: ctype,
                    'groups__%s__object_pk' % group_rel_name: obj.pk,
                }
            else:
                group_filters = {
                    'groups__%s__content_object' % group_rel_name: obj,
                }
            qset = qset | Q(**group_filters)
        if with_superusers:
            qset = qset | Q(is_superuser=True)
        return get_user_model().objects.filter(qset).distinct()

    user_model = get_user_model()
    users = {}

    # get all users with permissions to this object
    users_with_perms = get_users_with_perms(
        obj,
        with_group_users=with_group_users
    )
    # TODO: do paging on queryset here. This would likely
    # be from additional params passed in (page, page_size)

    user_ids = users_with_perms.values_list(user_model._meta.pk.name,
                                            flat=True)

    # then get all permissions for these users
    permissions_for_users = UserObjectPermission.objects.filter(
        user_id__in=user_ids,
        content_type_id=ContentType.objects.get_for_model(obj),
        object_pk=obj.id
    )

    # add the user keys for users who have access
    for user in users_with_perms:
        users[user] = []

    # sort through all the permissions for users
    for perm in permissions_for_users:
        user_model_kwargs = {user_model._meta.pk.name: perm.user_id}
        users[user_model(**user_model_kwargs)].append(perm.permission.codename)

    return users