示例#1
0
    def render(self, context):
        for_whom = self.for_whom.resolve(context)
        if isinstance(for_whom, get_user_model()):
            self.user = for_whom
            self.group = None
        elif isinstance(for_whom, AnonymousUser):
            self.user = get_user_model().get_anonymous()
            self.group = None
        elif isinstance(for_whom, Group):
            self.user = None
            self.group = for_whom
        elif isinstance(for_whom, Organization):
            self.user = None
            self.group = for_whom
        else:
            raise NotUserNorGroup("User or Group instance required (got %s)"
                                  % for_whom.__class__)
        obj = self.obj.resolve(context)
        if not obj:
            return ''

        check = ObjectPermissionChecker(for_whom)
        perms = check.get_perms(obj, include_group_perms=self.include_group_permissions)

        context[self.context_var] = perms
        return ''
示例#2
0
    def render(self, context):
        for_whom = self.for_whom.resolve(context)
        if isinstance(for_whom, get_user_model()):
            self.user = for_whom
            self.group = None
        elif isinstance(for_whom, AnonymousUser):
            self.user = get_user_model().get_anonymous()
            self.group = None
        elif isinstance(for_whom, Group):
            self.user = None
            self.group = for_whom
        elif isinstance(for_whom, Organization):
            self.user = None
            self.group = for_whom
        else:
            raise NotUserNorGroup("User or Group instance required (got %s)" %
                                  for_whom.__class__)
        obj = self.obj.resolve(context)
        if not obj:
            return ''

        check = ObjectPermissionChecker(for_whom)
        perms = check.get_perms(
            obj, include_group_perms=self.include_group_permissions)

        context[self.context_var] = perms
        return ''
示例#3
0
    def get_queryset(self, request):
        # Prefer the Django >= 1.6 interface but maintain
        # backward compatibility
        method = getattr(
            super(GuardedModelAdminMixin, self), 'get_queryset',
            getattr(super(GuardedModelAdminMixin, self), 'queryset', None))
        qs = method(request)

        if request.user.is_superuser:
            return qs

        if self.user_can_access_owned_objects_only:
            filters = {self.user_owned_objects_field: request.user}
            qs = qs.filter(**filters)
        if self.user_can_access_owned_by_group_objects_only:
            User = get_user_model()
            user_rel_name = User.groups.field.related_query_name()
            qs_key = '%s__%s' % (self.group_owned_objects_field, user_rel_name)
            filters = {qs_key: request.user}
            qs = qs.filter(**filters)
        if self.user_can_access_owned_by_organization_objects_only:
            User = get_user_model()
            m = OrgManager()
            qs = m.get_for_user(request.user)
        return qs
示例#4
0
文件: admin.py 项目: zztemp001/yaayaa
 def clean_user(self):
     """
     Returns ``User`` instance based on the given username.
     """
     username = self.cleaned_data['user']
     try:
         user = get_user_model().objects.get(username=username)
         return user
     except get_user_model().DoesNotExist:
         raise forms.ValidationError(
             self.fields['user'].error_messages['does_not_exist'])
示例#5
0
 def clean_user(self):
     """
     Returns ``User`` instance based on the given username.
     """
     username = self.cleaned_data['user']
     try:
         user = get_user_model().objects.get(username=username)
         return user
     except get_user_model().DoesNotExist:
         raise forms.ValidationError(
             self.fields['user'].error_messages['does_not_exist'])
示例#6
0
 def clean_user(self):
     """
     Returns ``User`` instance based on the given username.
     """
     username = self.cleaned_data['user']
     try:
         lookup = {getattr(get_user_model(), 'USERNAME_FIELD', 'username'): username}
         user = get_user_model().objects.get(**lookup)
         return user
     except get_user_model().DoesNotExist:
         raise forms.ValidationError(
             self.fields['user'].error_messages['does_not_exist'])
示例#7
0
 def setUp(self):
     self.ctype = ContentType.objects.create(name='foo', model='bar',
         app_label='fake-for-guardian-tests')
     self.factory = RequestFactory()
     self.user = get_user_model().objects.create_user(
         'joe', '*****@*****.**', 'doe')
     self.client.login(username='******', password='******')
示例#8
0
def get_users_for_object(object, permission, group=None, with_anonymous = False, with_group_users=False):
    """
    Returns list of users(worn:not QuerySet) with specific permission for this object
    :param obejct: model object to check permission
    :param permission: permission string
    :param group: group name for filter
    :param with_anonimous: add anonimous user to return value if it has permission on object, if group is set
    """

    anonymous_user = get_user_model().get_anonymous()

    anyperm = get_users_with_perms(object, attach_perms=True, with_group_users=with_group_users)
    if not isinstance(permission, list):
        permission = [permission]
    result = []
    for user, perms in anyperm.items():
        if set(permission).intersection(set(perms)):
            if group:
                if not isinstance(group, list):
                    group = [group]
                userGroups = user.groups.values_list('name', flat=True)
                if set(group).intersection(set(userGroups)):
                    result.append(user)
                if with_anonymous and user.is_anonymous:
                    result.append(user)
            else:
                result.append(user)
            if user.pk == anonymous_user.pk and with_anonymous:
                if user not in result:
                    result.append(user)

    return result
 def setUp(self):
     self.ctype = ContentType.objects.create(
         name='foo', model='bar', app_label='fake-for-guardian-tests')
     self.factory = RequestFactory()
     self.user = get_user_model().objects.create_user(
         'joe', '*****@*****.**', 'doe')
     self.client.login(username='******', password='******')
示例#10
0
    def get_organization_filters(self, obj, permission_expiry=False):
        User = get_user_model()
        ctype = get_content_type(obj)

        # Django organizations
        organization_model = get_organization_obj_perms_model(obj)
        organization_rel_name = organization_model.permission.field.related_query_name()
        if self.user:
            fieldname = '%s__organization__%s' % (
                organization_rel_name,
                "users",
            )
            organization_filters = {fieldname: self.user}
        else:
            organization_filters = {'%s__organization' % organization_rel_name: self.organization}
        if organization_model.objects.is_generic():
            organization_filters.update({
                '%s__content_type' % organization_rel_name: ctype,
                '%s__object_pk' % organization_rel_name: obj.pk,
            })
        else:
            organization_filters['%s__content_object' % organization_rel_name] = obj

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

        return organization_filters, org_q
示例#11
0
def get_anonymous_user():
    """
    Returns ``User`` instance (not ``AnonymousUser``) depending on
    ``ANONYMOUS_USER_NAME`` configuration.
    """
    return get_user_model().objects.get(
        username=guardian_settings.ANONYMOUS_USER_NAME)
示例#12
0
def get_viewers_for_object(object, user, permissions, with_anonymous=True):
    """
    Return viewers user by permission on object and by current g3w-suite user
    :param object: object to check permission
    :param user: current g3w-suite user in session
    :param permissions: permission to check, permission must is without app name, i.e. core.view_group become view_group
    :param with_anonymous: if add anonymous user to viewers list
    :return: viewers object list
    """

    editor1_viewers = None
    if userHasGroups(user, [G3W_EDITOR1]):
        editor1_viewers = get_objects_for_user(user, 'auth.change_user', User) \
            .filter(groups__name__in=[G3W_VIEWER1, G3W_VIEWER2])
        if with_anonymous:
            editor1_viewers |= User.objects.filter(
                pk=get_user_model().get_anonymous().pk)
    viewers = get_users_for_object(object,
                                   permissions, [G3W_VIEWER1, G3W_VIEWER2],
                                   with_anonymous=with_anonymous)

    if editor1_viewers:
        viewers = list(set(editor1_viewers).intersection(set(viewers)))

    if user in viewers:
        viewers.remove(user)

    return viewers
示例#13
0
    def assign_perm(self, perm, group, obj):
        """
        Assigns permission with given ``perm`` for an instance ``obj`` and
        ``group``.
        """
        if getattr(obj, 'pk', None) is None:
            raise ObjectNotPersisted("Object %s needs to be persisted first"
                % obj)
        ctype = ContentType.objects.get_for_model(obj)
        permission = Permission.objects.get(content_type=ctype, codename=perm)

        kwargs = {'permission': permission, 'group': group}
        if self.is_generic():
            kwargs['content_type'] = ctype
            kwargs['object_pk'] = obj.pk
        else:
            kwargs['content_object'] = obj
        obj_perm, created = self.get_or_create(**kwargs)

        # Add to cache
        check = ObjectPermissionChecker(group)
        key = check.get_local_cache_key(obj)
        cache_perms = cache.get(key)
        if cache_perms is not None and perm not in cache_perms:
            cache_perms.append(perm)
            cache.set(key, cache_perms)

        User = get_user_model()
        users = User.objects.filter(groups = group)
        for user in users:
            check = ObjectPermissionChecker(user)
            key = check.get_local_cache_key(obj)
            cache.delete(key)

        return obj_perm
示例#14
0
    def obj_perms_manage_user_view(self, request, object_pk, user_id):
        """
        Manages selected users' permissions for current object.
        """
        user = get_object_or_404(get_user_model(), pk=user_id)
        obj = get_object_or_404(self.queryset(request), pk=object_pk)
        form_class = self.get_obj_perms_manage_user_form()
        form = form_class(user, obj, request.POST or None)

        if request.method == 'POST' and form.is_valid():
            form.save_obj_perms()
            msg = ugettext("Permissions saved.")
            messages.success(request, msg)
            info = (
                self.admin_site.name,
                self.model._meta.app_label,
                get_model_name(self.model)
            )
            url = reverse(
                '%s:%s_%s_permissions_manage_user' % info,
                args=[obj.pk, user.pk]
            )
            return redirect(url)

        context = self.get_obj_perms_base_context(request, obj)
        context['user_obj'] = user
        context['user_perms'] = get_perms(user, obj)
        context['form'] = form

        return render_to_response(self.get_obj_perms_manage_user_template(),
            context, RequestContext(request, current_app=self.admin_site.name))
示例#15
0
 def setUp(self):
     self.article = Article.objects.create(title='foo-title',
                                           slug='foo-slug',
                                           content='bar-content')
     self.factory = RequestFactory()
     self.user = get_user_model().objects.create_user(
         'joe', '*****@*****.**', 'doe')
     self.client.login(username='******', password='******')
示例#16
0
 def setUp(self):
     self.article = Article.objects.create(title='foo-title',
                                           slug='foo-slug',
                                           content='bar-content')
     self.factory = RequestFactory()
     self.user = get_user_model().objects.create_user(
         'joe', '*****@*****.**', 'doe')
     self.client.login(username='******', password='******')
示例#17
0
def get_anonymous_user():
    """
    Returns ``User`` instance (not ``AnonymousUser``) depending on
    ``ANONYMOUS_USER_NAME`` configuration.
    """
    User = get_user_model()
    lookup = {User.USERNAME_FIELD: guardian_settings.ANONYMOUS_USER_NAME}
    return User.objects.get(**lookup)
示例#18
0
def get_anonymous_user():
    """
    Returns ``User`` instance (not ``AnonymousUser``) depending on
    ``ANONYMOUS_USER_NAME`` configuration.
    """
    User = get_user_model()
    lookup = {User.USERNAME_FIELD: guardian_settings.ANONYMOUS_USER_NAME}
    return User.objects.get(**lookup)
示例#19
0
    def clean_user(self):
        """
        Returns ``User`` instance based on the given identification.
        """
        s = self.cleaned_data['user']
        user_model = get_user_model()
        try:
            username_field = user_model.USERNAME_FIELD
        except AttributeError:
            username_field = 'username'
        try:
            users = get_user_model().objects.filter(
                Q(username__icontains=s) | Q(first_name__icontains=s) | Q(last_name__icontains=s))[:20]
            return users

        except user_model.DoesNotExist:
            raise forms.ValidationError(
                self.fields['user'].error_messages['does_not_exist'])
def add_view_surveyassginemnt_perms(apps, schema_editor):
    SurveyAssignment = apps.get_model('survey', 'SurveyAssignment')
    survey_assignments = SurveyAssignment.objects.all()
    User = get_user_model()
    for assigned_survey in survey_assignments:
        assignee = assigned_survey.assigned_to
        user = User.objects.get(pk=assignee.id)
        if not user.has_perm('view_surveyassignment', assigned_survey):
            assign_perm('view_surveyassignment', user, assigned_survey)
示例#21
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
示例#22
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
示例#23
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
示例#24
0
def get_users_with_perms(obj, attach_perms=False, with_superusers=False,
                         with_group_users=True, permission_expiry=False):
        """
        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']}

        """
        if not attach_perms:
            qset = get_unattached_users_with_perms_qset(obj, None,
                                                        with_group_users=with_group_users,
                                                        with_superusers=with_superusers,
                                                        permission_expiry=permission_expiry
                                                        )
            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,
                                             permission_expiry=permission_expiry):
                # 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
示例#25
0
    def test_uses_custom_username_field_model(self, guardian_settings):
        mocked_get_init_anon.reset_mock()
        guardian_settings.GET_INIT_ANONYMOUS_USER = '******'
        guardian_settings.ANONYMOUS_USER_NAME = '*****@*****.**'
        User = get_user_model()

        anon = mocked_get_init_anon.return_value = mock.Mock()
        create_anonymous_user('sender')
        mocked_get_init_anon.assert_called_once_with(User)
        anon.save.assert_called_once_with()
示例#26
0
def create_anonymous_user(sender, **kwargs):
    """
    Creates anonymous User instance with id from settings.
    """
    User = get_user_model()
    try:
        User.objects.get(pk=guardian_settings.ANONYMOUS_USER_ID)
    except User.DoesNotExist:
        User.objects.create(pk=guardian_settings.ANONYMOUS_USER_ID,
            username='******')
示例#27
0
    def test_uses_custom_username_field_model(self, guardian_settings):
        mocked_get_init_anon.reset_mock()
        guardian_settings.GET_INIT_ANONYMOUS_USER = '******'
        guardian_settings.ANONYMOUS_USER_NAME = '*****@*****.**'
        User = get_user_model()

        anon = mocked_get_init_anon.return_value = mock.Mock()
        create_anonymous_user('sender')
        mocked_get_init_anon.assert_called_once_with(User)
        anon.save.assert_called_once_with()
示例#28
0
def get_users_with_permission(obj, permission):
    """Return users with specific permission on object.

    :param obj: Object to return users for
    :param permission: Permission codename
    """
    user_model = get_user_model()
    return user_model.objects.filter(
        userobjectpermission__object_pk=obj.pk,
        userobjectpermission__permission__codename=permission,
    ).distinct()
示例#29
0
    def obj_perms_manage_view(self, request, object_pk):
        """
        Main object permissions view. Presents all users and groups with any
        object permissions for the current model *instance*. Users or groups
        without object permissions for related *instance* would **not** be
        shown. In order to add or manage user or group one should use links or
        forms presented within the page.
        """
        obj = get_object_or_404(self.queryset(request), pk=object_pk)
        users_perms = SortedDict(
            get_users_with_perms(obj,
                                 attach_perms=True,
                                 with_group_users=False))

        users_perms.keyOrder.sort(
            key=lambda user: getattr(user,
                                     get_user_model().USERNAME_FIELD))
        groups_perms = SortedDict(get_groups_with_perms(obj,
                                                        attach_perms=True))
        groups_perms.keyOrder.sort(key=lambda group: group.name)

        if request.method == 'POST' and 'submit_manage_user' in request.POST:
            user_form = UserManage(request.POST)
            group_form = GroupManage()
            info = (self.admin_site.name, self.model._meta.app_label,
                    self.model._meta.module_name)
            if user_form.is_valid():
                user_id = user_form.cleaned_data['user'].pk
                url = reverse('%s:%s_%s_permissions_manage_user' % info,
                              args=[obj.pk, user_id])
                return redirect(url)
        elif request.method == 'POST' and 'submit_manage_group' in request.POST:
            user_form = UserManage()
            group_form = GroupManage(request.POST)
            info = (self.admin_site.name, self.model._meta.app_label,
                    self.model._meta.module_name)
            if group_form.is_valid():
                group_id = group_form.cleaned_data['group'].id
                url = reverse('%s:%s_%s_permissions_manage_group' % info,
                              args=[obj.pk, group_id])
                return redirect(url)
        else:
            user_form = UserManage()
            group_form = GroupManage()

        context = self.get_obj_perms_base_context(request, obj)
        context['users_perms'] = users_perms
        context['groups_perms'] = groups_perms
        context['user_form'] = user_form
        context['group_form'] = group_form

        return render_to_response(
            self.get_obj_perms_manage_template(), context,
            RequestContext(request, current_app=self.admin_site.name))
示例#30
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 assign_can_view_survey_results_perms(apps, schema_editor):
    User = get_user_model()
    Survey = apps.get_model('survey', 'Survey')
    ContentType = apps.get_model('contenttypes', 'ContentType')
    Permission = apps.get_model('auth', 'Permission')
    surveys = Survey.objects.all()
    for survey in surveys:
        group_name = f"survey_{survey.id}_result_viewers"
        group = Group.objects.create(name=group_name)
        assign_perm(PERMISSION_FULL_NAME, group, survey)
        creator = User.objects.get(pk=survey.created_by.id)
        creator.groups.add(group)
        creator.save()
示例#32
0
def create_anonymous_user(sender, **kwargs):
    """
    Creates anonymous User instance with id and username from settings.
    """
    User = get_user_model()
    try:
        lookup = {User.USERNAME_FIELD: guardian_settings.ANONYMOUS_USER_NAME}
        User.objects.get(**lookup)
    except User.DoesNotExist:
        retrieve_anonymous_function = import_string(
            guardian_settings.GET_INIT_ANONYMOUS_USER)
        user = retrieve_anonymous_function(User)
        user.save()
示例#33
0
    def render(self, context):
        for_whom = self.for_whom.resolve(context)
        if isinstance(for_whom, get_user_model()):
            self.user = for_whom
            self.group = None
        elif isinstance(for_whom, AnonymousUser):
            self.user = get_user_model().get_anonymous()
            self.group = None
        elif isinstance(for_whom, Group):
            self.user = None
            self.group = for_whom
        else:
            raise NotUserNorGroup("User or Group instance required (got %s)"
                % for_whom.__class__)
        obj = self.obj.resolve(context)

        check = ObjectPermissionChecker(for_whom)
        perms = check.get_perms(obj)
        perms += [ap.split('.')[1] for ap in list(get_uog_permissions(self.user, obj))]

        context[self.context_var] = perms
        return ''
示例#34
0
    def test_uses_custom_function(self, guardian_settings):
        path = 'guardian.testapp.tests.management_test.mocked_get_init_anon'
        guardian_settings.GET_INIT_ANONYMOUS_USER = path
        guardian_settings.ANONYMOUS_USER_ID = 219
        User = get_user_model()

        anon = mocked_get_init_anon.return_value = mock.Mock()

        create_anonymous_user('sender')

        mocked_get_init_anon.assert_called_once_with(User)

        self.assertEqual(anon.pk, 219)
        anon.save.assert_called_once_with()
示例#35
0
def create_anonymous_user(sender, **kwargs):
    """
    Creates anonymous User instance with id and username from settings.
    """
    User = get_user_model()
    try:
        User.objects.get(pk=guardian_settings.ANONYMOUS_USER_ID)
    except User.DoesNotExist:
        if django.VERSION >= (1, 5):
            User.objects.create(pk=guardian_settings.ANONYMOUS_USER_ID,
                **{User.USERNAME_FIELD: guardian_settings.ANONYMOUS_DEFAULT_USERNAME_VALUE})
        else:
            User.objects.create(pk=guardian_settings.ANONYMOUS_USER_ID,
                username=guardian_settings.ANONYMOUS_DEFAULT_USERNAME_VALUE)
示例#36
0
def get_users_with_permission(obj, perm, attach_perms=False, with_superusers=False,
                         with_group_users=True, permission_expiry=False):
    qset = get_unattached_users_with_perms_qset(obj, perm,
         with_group_users=with_group_users,
         with_superusers=with_superusers,
         permission_expiry=permission_expiry
    )
    if not attach_perms:
        user_model = get_user_obj_perms_model(obj)
        related_name = user_model.user.field.related_query_name()
        ret = get_user_model().objects.filter(qset).distinct()
        return ret
    else:
        raise NotImplementedError
def create_anonymous_user(sender, **kwargs):
    """
    Creates anonymous User instance with id and username from settings.
    """
    User = get_user_model()
    try:
        User.objects.get(pk=guardian_settings.ANONYMOUS_USER_ID)
    except User.DoesNotExist:
        retrieve_anonymous_function = import_string(
            guardian_settings.GET_INIT_ANONYMOUS_USER)
        user = retrieve_anonymous_function(User)
        # Always set pk to the one pointed at settings
        user.pk = guardian_settings.ANONYMOUS_USER_ID
        user.save()
示例#38
0
    def has_perm(self, user_obj, perm, obj=None, groups_filter=None):
        """
        Returns ``True`` if given ``user_obj`` has ``perm`` for ``obj``. If no
        ``obj`` is given, ``False`` is returned.

        .. note::

           Remember, that if user is not *active*, all checks would return
           ``False``.

        Main difference between Django's ``ModelBackend`` is that we can pass
        ``obj`` instance here and ``perm`` doesn't have to contain
        ``app_label`` as it can be retrieved from given ``obj``.

        **Inactive user support**

        If user is authenticated but inactive at the same time, all checks
        always returns ``False``.
        """
        # Backend checks only object permissions
        if obj is None:
            return False

        # Backend checks only permissions for Django models
        if not isinstance(obj, models.Model):
            return False

        # This is how we support anonymous users - simply try to retrieve User
        # instance and perform checks for that predefined user
        if not user_obj.is_authenticated():
            # If anonymous user permission is disabled then they are always
            # unauthorized
            if settings.ANONYMOUS_USER_ID is None:
                return False
            user_obj = get_user_model().objects.get(
                pk=settings.ANONYMOUS_USER_ID)

        # Do not check any further if user is not active
        if not user_obj.is_active:
            return False

        if len(perm.split('.')) > 1:
            app_label, perm = perm.split('.')
            if app_label != obj._meta.app_label:
                raise WrongAppError(
                    "Passed perm has app label of '%s' and "
                    "given obj has '%s'" % (app_label, obj._meta.app_label))

        check = ObjectPermissionChecker(user_obj)
        return check.has_perm(perm, obj, groups_filter=groups_filter)
示例#39
0
 def clean_user(self):
     """
     Returns ``User`` instance based on the given identification.
     """
     identification = self.cleaned_data['user']
     user_model = get_user_model()
     
     try:
         username_field = user_model.USERNAME_FIELD
         user = user_model.objects.get(**{username_field: identification})
         return user
     except user_model.DoesNotExist:
         raise forms.ValidationError(
             self.fields['user'].error_messages['does_not_exist'])
示例#40
0
def create_anonymous_user(sender, **kwargs):
    """
    Creates anonymous User instance with id and username from settings.
    """
    User = get_user_model()
    try:
        User.objects.get(pk=guardian_settings.ANONYMOUS_USER_ID)
    except User.DoesNotExist:
        retrieve_anonymous_function = import_string(
            guardian_settings.GET_INIT_ANONYMOUS_USER)
        user = retrieve_anonymous_function(User)
        # Always set pk to the one pointed at settings
        user.pk = guardian_settings.ANONYMOUS_USER_ID
        user.save()
示例#41
0
def create_anonymous_user(sender, **kwargs):
    """
    Creates anonymous User instance with id and username from settings.
    """
    User = get_user_model()
    try:
        User.objects.get(pk=guardian_settings.ANONYMOUS_USER_ID)
    except User.DoesNotExist:
        if django.VERSION >= (1, 5):
            User.objects.create(pk=guardian_settings.ANONYMOUS_USER_ID,
                **{User.USERNAME_FIELD: guardian_settings.ANONYMOUS_DEFAULT_USERNAME_VALUE})
        else:
            User.objects.create(pk=guardian_settings.ANONYMOUS_USER_ID,
                username=guardian_settings.ANONYMOUS_DEFAULT_USERNAME_VALUE)
示例#42
0
    def test_uses_custom_function(self, guardian_settings):
        mocked_get_init_anon.reset_mock()

        path = 'guardian.testapp.tests.test_management.mocked_get_init_anon'
        guardian_settings.GET_INIT_ANONYMOUS_USER = path
        guardian_settings.ANONYMOUS_USER_NAME = "anonymous"
        User = get_user_model()

        anon = mocked_get_init_anon.return_value = mock.Mock()

        create_anonymous_user('sender')

        mocked_get_init_anon.assert_called_once_with(User)

        anon.save.assert_called_once_with()
示例#43
0
    def test_uses_custom_function(self, guardian_settings):
        mocked_get_init_anon.reset_mock()

        path = 'guardian.testapp.tests.test_management.mocked_get_init_anon'
        guardian_settings.GET_INIT_ANONYMOUS_USER = path
        guardian_settings.ANONYMOUS_USER_NAME = "anonymous"
        User = get_user_model()

        anon = mocked_get_init_anon.return_value = mock.Mock()

        create_anonymous_user('sender')

        mocked_get_init_anon.assert_called_once_with(User)

        anon.save.assert_called_once_with()
示例#44
0
文件: admin.py 项目: zztemp001/yaayaa
    def queryset(self, request):
        qs = super(GuardedModelAdmin, self).queryset(request)
        if request.user.is_superuser:
            return qs

        if self.user_can_access_owned_objects_only:
            filters = {self.user_owned_objects_field: request.user}
            qs = qs.filter(**filters)
        if self.user_can_access_owned_by_group_objects_only:
            User = get_user_model()
            user_rel_name = User.groups.field.related_query_name()
            qs_key = '%s__%s' % (self.group_owned_objects_field, user_rel_name)
            filters = {qs_key: request.user}
            qs = qs.filter(**filters)
        return qs
示例#45
0
    def queryset(self, request):
        qs = super(GuardedModelAdmin, self).queryset(request)
        if request.user.is_superuser:
            return qs

        if self.user_can_access_owned_objects_only:
            filters = {self.user_owned_objects_field: request.user}
            qs = qs.filter(**filters)
        if self.user_can_access_owned_by_group_objects_only:
            User = get_user_model()
            user_rel_name = User.groups.field.related_query_name()
            qs_key = '%s__%s' % (self.group_owned_objects_field, user_rel_name)
            filters = {qs_key: request.user}
            qs = qs.filter(**filters)
        return qs
示例#46
0
 def clean_user(self):
     """
     Returns ``User`` instance based on the given identification.
     """
     identification = self.cleaned_data['user']
     user_model = get_user_model()
     try:
         username_field = user_model.USERNAME_FIELD
     except AttributeError:
         username_field = 'username'
     try:
         user = user_model.objects.get(**{username_field: identification})
         return user
     except user_model.DoesNotExist:
         raise forms.ValidationError(
             self.fields['user'].error_messages['does_not_exist'])
示例#47
0
def load_initial_data():
    flush_vavilov_tables()
    User = get_user_model()
    anon = User.get_anonymous()
    public_group = get_or_create_public_group()
    public_group.user_set.add(anon)
    non_public_permissions = [
        'View Observation', 'View observation images',
        'View Observation Relationship', 'View Observation entity'
    ]

    if not ACCESSIONS_ARE_PUBLIC:
        non_public_permissions.append('View Accession')
    add_view_permissions(anon, filter_perms=non_public_permissions)

    load_initial_data_from_dict(SHARED_INITIAL_DATA_TO_LOAD)
示例#48
0
def _create_webservice_user_for_site(sender, instance, created, *args,
                                     **kwargs):
    if created:
        from django.contrib.auth import get_user_model

        user = get_user_model().objects.create_user(
            username='******'.format(
                settings.WEBSERVICE_USERNAME_PREFIX,
                instance.slug),
            email='',
            password=instance.slug,
            first_name=instance.first_name,
            last_name=instance.last_name)
        group = Group.objects.get(name='WebService')
        # create siteaccess
        BluuSiteAccess.objects.create(site=instance, group=group, user=user)
示例#49
0
def get_users_with_perms(obj,
                         attach_perms=True,
                         with_superusers=True,
                         with_group_users=True):
    all_user_perms = dict()

    #Retrieve superusers
    if with_superusers:
        superusers = get_user_model().objects.filter(Q(is_superuser=True))
        for s_user in superusers:
            all_user_perms[s_user] = sorted(get_perms(s_user, obj))

    #Retrieve users with direct permissions
    obj_content_type = ContentType.objects.get_for_model(obj)
    user_perms = guardian.models.UserObjectPermission.objects.filter(
        content_type=obj_content_type, object_pk=obj.id)
    for p in user_perms:
        if p.user in all_user_perms:
            bisect.insort_left(all_user_perms[p.user], p.permission.codename)
        else:
            all_user_perms[p.user] = [p.permission.codename]
    #Retrieve users with permissions via group
    if with_group_users:
        group_perms = get_groups_with_perms(obj, )
        for g, perms in group_perms.iteritems():  #Iterate over each group
            if g.name == "anonymous":
                for g_user in g.user_set.all(
                ):  #Iterate over each user in each group
                    if g_user in all_user_perms:
                        current_perms = list(all_user_perms[g_user])
                        current_perms.extend(p for p in perms
                                             if p not in current_perms)
                        all_user_perms[g_user] = sorted(current_perms)
                    else:
                        all_user_perms[g_user] = sorted(perms)
            else:
                for g_mem in g.groupprofile.member_queryset(
                ):  # Iterate over group members using group profile
                    user = g_mem.user
                    if user in all_user_perms:  # Add unique permissions not found in current perms of user
                        current_perms = list(all_user_perms[user])
                        current_perms.extend(p for p in perms
                                             if p not in current_perms)
                        all_user_perms[user] = sorted(current_perms)
                    else:
                        all_user_perms[user] = sorted(perms)
    return all_user_perms
示例#50
0
    def has_perm(self, user_obj, perm, obj=None):
        """
        Returns ``True`` if given ``user_obj`` has ``perm`` for ``obj``. If no
        ``obj`` is given, ``False`` is returned.

        .. note::

           Remember, that if user is not *active*, all checks would return
           ``False``.

        Main difference between Django's ``ModelBackend`` is that we can pass
        ``obj`` instance here and ``perm`` doesn't have to contain
        ``app_label`` as it can be retrieved from given ``obj``.

        **Inactive user support**

        If user is authenticated but inactive at the same time, all checks
        always returns ``False``.
        """
        # Backend checks only object permissions
        if obj is None:
            return False

        # Backend checks only permissions for Django models
        if not isinstance(obj, models.Model):
            return False

        # This is how we support anonymous users - simply try to retrieve User
        # instance and perform checks for that predefined user
        if not user_obj.is_authenticated():
            # If anonymous user permission is disabled then they are always unauthorized
            if settings.ANONYMOUS_USER_ID is None:
                return False
            user_obj = get_user_model().objects.get(pk=settings.ANONYMOUS_USER_ID)

        # Do not check any further if user is not active
        if not user_obj.is_active:
            return False

        if len(perm.split('.')) > 1:
            app_label, perm = perm.split('.')
            if app_label != obj._meta.app_label:
                raise WrongAppError("Passed perm has app label of '%s' and "
                    "given obj has '%s'" % (app_label, obj._meta.app_label))

        check = ObjectPermissionChecker(user_obj)
        return check.has_perm(perm, obj)
示例#51
0
    def get_site_managers(self):
        """
        Returns queryset of all ``User`` objects with
        *bluusites.change_bluusite* object permissions for current bluusite.
        """
        ctype = ContentType.objects.get_for_model(self)
        related_name = 'userobjectgroup'
        user_filters = {
                '%s__content_type' % related_name: ctype,
                '%s__object_pk' % related_name: self.pk,
                '%s__group__permissions__content_type' % related_name: ctype,
                '%s__group__permissions__codename' % related_name: 'change_bluusite',
            }
        qset = Q(**user_filters)

        return get_user_model().objects.filter(qset).exclude(
            userobjectgroup__group__name='WebService').distinct()
示例#52
0
def check_user_support(user_obj):
    """
    Returns a tuple of checkresult and ``user_obj`` which should be used for
    permission checks

    Checks if the given user is supported. Anonymous users need explicit
    activation via ANONYMOUS_USER_ID
    """
    # This is how we support anonymous users - simply try to retrieve User
    # instance and perform checks for that predefined user
    if not user_obj.is_authenticated():
        # If anonymous user permission is disabled then they are always unauthorized
        if settings.ANONYMOUS_USER_ID is None:
            return False, user_obj
        user_obj = get_user_model().objects.get(pk=settings.ANONYMOUS_USER_ID)

    return True, user_obj
示例#53
0
    def get_queryset(self, request):
        # Prefer the Django >= 1.6 interface but maintain
        # backward compatibility
        method = getattr(super(GuardedModelAdminMixin, self), 'get_queryset',
                         super(GuardedModelAdminMixin, self).queryset)
        qs = method(request)

        if request.user.is_superuser:
            return qs

        if self.user_can_access_owned_objects_only:
            filters = {self.user_owned_objects_field: request.user}
            qs = qs.filter(**filters)
        if self.user_can_access_owned_by_group_objects_only:
            User = get_user_model()
            user_rel_name = User.groups.field.related_query_name()
            qs_key = '%s__%s' % (self.group_owned_objects_field, user_rel_name)
            filters = {qs_key: request.user}
            qs = qs.filter(**filters)
        return qs
示例#54
0
def get_identity(identity):
    """
    Returns (user_obj, None) or (None, group_obj) tuple depending on what is
    given. Also accepts AnonymousUser instance but would return ``User``
    instead - it is convenient and needed for authorization backend to support
    anonymous users.

    :param identity: either ``User`` or ``Group`` instance

    :raises ``NotUserNorGroup``: if cannot return proper identity instance

    **Examples**::

       >>> from django.contrib.auth.models import User
       >>> user = User.objects.create(username='******')
       >>> get_identity(user)
       (<User: joe>, None)

       >>> group = Group.objects.create(name='users')
       >>> get_identity(group)
       (None, <Group: users>)

       >>> anon = AnonymousUser()
       >>> get_identity(anon)
       (<User: AnonymousUser>, None)

       >>> get_identity("not instance")
       ...
       NotUserNorGroup: User/AnonymousUser or Group instance is required (got )

    """
    if isinstance(identity, AnonymousUser):
        identity = get_anonymous_user()

    if isinstance(identity, get_user_model()):
        return identity, None
    elif isinstance(identity, Group):
        return None, identity

    raise NotUserNorGroup("User/AnonymousUser or Group instance is required "
        "(got %s)" % identity)
示例#55
0
    def removePermissionsToViewers(self, users_id):
        """
        Remove guardian permissions to Viewers
        """
        appProjects = getProjectsByGroup(self)

        # anonynous users id
        anonymous_uid = get_user_model().get_anonymous().pk

        for user_id in users_id:
            setPermissionUserObject(User.objects.get(pk=user_id),
                                    self,
                                    permissions='view_group',
                                    mode='remove')

            # adding permissions to projects
            # not for anonymous user, who exit from this flow
            if user_id != anonymous_uid:
                for app, projects in list(appProjects.items()):
                    for project in projects:
                        project.removePermissionsToViewers(users_id)
示例#56
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