Beispiel #1
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,
                    get_model_name(self.model))
            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,
                    get_model_name(self.model))
            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))
Beispiel #2
0
    def get_urls(self):
        """
        Extends standard admin model urls with the following:

        - ``.../permissions/`` under ``app_mdodel_permissions`` url name (params: object_pk)
        - ``.../permissions/user-manage/<user_id>/`` under ``app_model_permissions_manage_user`` url name (params: object_pk, user_pk)
        - ``.../permissions/group-manage/<group_id>/`` under ``app_model_permissions_manage_group`` url name (params: object_pk, group_pk)

        .. note::
           ``...`` above are standard, instance detail url (i.e.
           ``/admin/flatpages/1/``)

        """
        urls = super(GuardedModelAdminMixin, self).get_urls()
        if self.include_object_permissions_urls:
            info = self.model._meta.app_label, get_model_name(self.model)
            myurls = [
                url(r'^(?P<object_pk>.+)/permissions/$',
                    view=self.admin_site.admin_view(
                        self.obj_perms_manage_view),
                    name='%s_%s_permissions' % info),
                url(r'^(?P<object_pk>.+)/permissions/user-manage/(?P<user_id>\-?\d+)/$',
                    view=self.admin_site.admin_view(
                        self.obj_perms_manage_user_view),
                    name='%s_%s_permissions_manage_user' % info),
                url(r'^(?P<object_pk>.+)/permissions/group-manage/(?P<group_id>\-?\d+)/$',
                    view=self.admin_site.admin_view(
                        self.obj_perms_manage_group_view),
                    name='%s_%s_permissions_manage_group' % info),
            ]
            urls = myurls + urls
        return urls
Beispiel #3
0
    def get_urls(self):
        """
        Extends standard admin model urls with the following:

        - ``.../permissions/`` under ``app_mdodel_permissions`` url name (params: object_pk)
        - ``.../permissions/user-manage/<user_id>/`` under ``app_model_permissions_manage_user`` url name (params: object_pk, user_pk)
        - ``.../permissions/group-manage/<group_id>/`` under ``app_model_permissions_manage_group`` url name (params: object_pk, group_pk)

        .. note::
           ``...`` above are standard, instance detail url (i.e.
           ``/admin/flatpages/1/``)

        """
        urls = super(GuardedModelAdminMixin, self).get_urls()
        if self.include_object_permissions_urls:
            info = self.model._meta.app_label, get_model_name(self.model)
            myurls = [
                              url(r'^(?P<object_pk>.+)/permissions/$',
                                  view=self.admin_site.admin_view(self.obj_perms_manage_view),
                                  name='%s_%s_permissions' % info),
                              url(r'^(?P<object_pk>.+)/permissions/user-manage/(?P<user_id>\-?\d+)/$',
                                  view=self.admin_site.admin_view(self.obj_perms_manage_user_view),
                                  name='%s_%s_permissions_manage_user' % info),
                              url(r'^(?P<object_pk>.+)/permissions/group-manage/(?P<group_id>\-?\d+)/$',
                                  view=self.admin_site.admin_view(self.obj_perms_manage_group_view),
                                  name='%s_%s_permissions_manage_group' % info),
                              ]
            urls = myurls + urls
        return urls
Beispiel #4
0
    def obj_perms_manage_group_view(self, request, object_pk, group_id):
        """
        Manages selected groups' permissions for current object.
        """
        group = get_object_or_404(Group, id=group_id)
        obj = get_object_or_404(self.queryset(request), pk=object_pk)
        form_class = self.get_obj_perms_manage_group_form()
        form = form_class(group, 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_group' % info,
                args=[obj.pk, group.id]
            )
            return redirect(url)

        context = self.get_obj_perms_base_context(request, obj)
        context['group_obj'] = group
        context['group_perms'] = get_perms(group, obj)
        context['form'] = form

        return render_to_response(self.get_obj_perms_manage_group_template(),
            context, RequestContext(request, current_app=self.admin_site.name))
Beispiel #5
0
    def obj_perms_manage_user_view(self, request, object_pk, user_id):
        """
        Manages selected users' permissions for current object.
        """
        if not self.has_change_permission(request, None):
            post_url = reverse('admin:index', current_app=self.admin_site.name)
            return redirect(post_url)

        user = get_object_or_404(get_user_model(), pk=user_id)
        obj = get_object_or_404(self.get_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

        request.current_app = self.admin_site.name

        return render_to_response(self.get_obj_perms_manage_user_template(),
                                  context, RequestContext(request))
Beispiel #6
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),
        )
 def setUp(self):
     self.admin = User.objects.create_superuser('admin', '*****@*****.**',
         'admin')
     self.user = User.objects.create_user('joe', '*****@*****.**', 'joe')
     self.group = Group.objects.create(name='group')
     self.client = Client()
     self.obj = ContentType.objects.create(model='bar', app_label='fake-for-guardian-tests')
     self.obj_info = self.obj._meta.app_label, get_model_name(self.obj)
Beispiel #8
0
 def setUp(self):
     self.admin = User.objects.create_superuser('admin', '*****@*****.**',
         'admin')
     self.user = User.objects.create_user('joe', '*****@*****.**', 'joe')
     self.group = Group.objects.create(name='group')
     self.client = Client()
     self.obj = ContentType.objects.create(model='bar', app_label='fake-for-guardian-tests')
     self.obj_info = self.obj._meta.app_label, get_model_name(self.obj)
Beispiel #9
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, get_model_name(self.model))
            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, get_model_name(self.model))
            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)
        )
Beispiel #10
0
    def obj_perms_manage_user_view(self, request, object_pk, user_id):
        """
        Manages selected users' permissions for current object.
        """
        if not self.has_change_permission(request, None):
            post_url = reverse('admin:index', current_app=self.admin_site.name)
            return redirect(post_url)

        user = get_object_or_404(get_user_model(), pk=user_id)
        obj = get_object_or_404(self.get_queryset(request), pk=object_pk)
        form_class = self.get_obj_perms_manage_user_form(request)
        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_user_perms(user, obj)
        context['form'] = form

        request.current_app = self.admin_site.name

        if django.VERSION >= (1, 10):
            return render(request, self.get_obj_perms_manage_user_template(), context)

        return render_to_response(self.get_obj_perms_manage_user_template(), context, RequestContext(request))
Beispiel #11
0
from guardian.shortcuts import get_users_with_perms
from guardian.shortcuts import get_groups_with_perms
from guardian.shortcuts import get_objects_for_user
from guardian.shortcuts import get_objects_for_group
from guardian.exceptions import MixedContentTypeError
from guardian.exceptions import NotUserNorGroup
from guardian.exceptions import WrongAppError
from guardian.testapp.models import NonIntPKModel
from guardian.testapp.tests.test_core import ObjectPermissionTestCase
from guardian.models import Group, Permission

import warnings

User = get_user_model()
user_app_label = User._meta.app_label
user_module_name = get_model_name(User)


class ShortcutsTests(ObjectPermissionTestCase):
    def test_get_perms_for_model(self):
        self.assertEqual(get_perms_for_model(self.user).count(), 3)
        self.assertTrue(
            list(get_perms_for_model(self.user)) == list(
                get_perms_for_model(User)))
        self.assertEqual(get_perms_for_model(Permission).count(), 3)

        model_str = 'contenttypes.ContentType'
        self.assertEqual(
            sorted(get_perms_for_model(model_str).values_list()),
            sorted(get_perms_for_model(ContentType).values_list()))
        obj = ContentType()
Beispiel #12
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.
        """
        if not self.has_change_permission(request, None):
            post_url = reverse('admin:index', current_app=self.admin_site.name)
            return redirect(post_url)

        try:
            # django >= 1.7
            from django.contrib.admin.utils import unquote
        except ImportError:
            # django < 1.7
            from django.contrib.admin.util import unquote
        obj = get_object_or_404(self.get_queryset(request),
                                pk=unquote(object_pk))
        users_perms = OrderedDict(
            sorted(get_users_with_perms(obj,
                                        attach_perms=True,
                                        with_group_users=False).items(),
                   key=lambda user: getattr(user[0],
                                            get_user_model().USERNAME_FIELD)))

        groups_perms = OrderedDict(
            sorted(get_groups_with_perms(obj, attach_perms=True).items(),
                   key=lambda group: group[0].name))

        if request.method == 'POST' and 'submit_manage_user' in request.POST:
            user_form = self.get_obj_perms_user_select_form(request)(
                request.POST)
            group_form = self.get_obj_perms_group_select_form(request)(
                request.POST)
            info = (self.admin_site.name, self.model._meta.app_label,
                    get_model_name(self.model))
            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 = self.get_obj_perms_user_select_form(request)(
                request.POST)
            group_form = self.get_obj_perms_group_select_form(request)(
                request.POST)
            info = (self.admin_site.name, self.model._meta.app_label,
                    get_model_name(self.model))
            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 = self.get_obj_perms_user_select_form(request)()
            group_form = self.get_obj_perms_group_select_form(request)()

        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

        # https://github.com/django/django/commit/cf1f36bb6eb34fafe6c224003ad585a647f6117b
        request.current_app = self.admin_site.name

        if django.VERSION >= (1, 10):
            return render(request, self.get_obj_perms_manage_template(),
                          context)

        return render_to_response(self.get_obj_perms_manage_template(),
                                  context, RequestContext(request))
Beispiel #13
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.
        """
        if not self.has_change_permission(request, None):
            post_url = reverse('admin:index', current_app=self.admin_site.name)
            return redirect(post_url)

        try:
            # django >= 1.7
            from django.contrib.admin.utils import unquote
        except ImportError:
            # django < 1.7
            from django.contrib.admin.util import unquote
        obj = get_object_or_404(self.get_queryset(request), pk=unquote(object_pk))
        users_perms = OrderedDict(
            sorted(
                list(get_users_with_perms(obj, attach_perms=True, with_group_users=False).items()),
                key=lambda user: getattr(user[0], get_user_model().USERNAME_FIELD)
            )
        )

        groups_perms = OrderedDict(
            sorted(
                list(get_groups_with_perms(obj, attach_perms=True).items()),
                key=lambda group: group[0].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,
                get_model_name(self.model)
            )
            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,
                get_model_name(self.model)
            )
            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

        # https://github.com/django/django/commit/cf1f36bb6eb34fafe6c224003ad585a647f6117b
        request.current_app = self.admin_site.name

        return render_to_response(self.get_obj_perms_manage_template(), context, RequestContext(request))
Beispiel #14
0
from guardian.shortcuts import get_groups_with_perms
from guardian.shortcuts import get_objects_for_user
from guardian.shortcuts import get_objects_for_group
from guardian.exceptions import MixedContentTypeError
from guardian.exceptions import NotUserNorGroup
from guardian.exceptions import WrongAppError
from guardian.testapp.models import NonIntPKModel
from guardian.testapp.tests.core_test import ObjectPermissionTestCase
from guardian.models import Group, Permission

import warnings


User = get_user_model()
user_app_label = User._meta.app_label
user_module_name = get_model_name(User)

class ShortcutsTests(ObjectPermissionTestCase):

    def test_get_perms_for_model(self):
        self.assertEqual(get_perms_for_model(self.user).count(), 3)
        self.assertTrue(list(get_perms_for_model(self.user)) ==
            list(get_perms_for_model(User)))
        self.assertEqual(get_perms_for_model(Permission).count(), 3)

        model_str = 'contenttypes.ContentType'
        self.assertEqual(
            sorted(get_perms_for_model(model_str).values_list()),
            sorted(get_perms_for_model(ContentType).values_list()))
        obj = ContentType()
        self.assertEqual(