admin.py 13.3 KB
Newer Older
Lincoln Smith's avatar
Lincoln Smith committed
1
from django.contrib import admin
2
3
4
from django.contrib import messages
from django.db import transaction
from django.contrib.auth import get_user_model
5
from django.contrib.auth.models import Permission
Lincoln Smith's avatar
Lincoln Smith committed
6
from django.conf.urls import url
7
from django.core.exceptions import ValidationError, ObjectDoesNotExist, PermissionDenied
8
9
10
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
from django.template.response import TemplateResponse
Lincoln Smith's avatar
Lincoln Smith committed
11
12
13
14
from functools import update_wrapper

from perfieldperms import forms
from perfieldperms import models
15
from perfieldperms.utils import get_m2m_remote_fields, get_manager_name, disable_fields
Lincoln Smith's avatar
Lincoln Smith committed
16

17
18

class PFPModelAdminMixin(admin.ModelAdmin):
19
20
21
22
    """
    Extends get_form() to disable fields based on user's field level
    permissions.
    """
23
24
    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
25
        return disable_fields(request, self.model, obj, form)
26
27
28


class PFPInlineAdminMixin(admin.options.InlineModelAdmin):
29
30
31
32
    """
    Extends get_formset() to disable fields based on user's field level
    permissions.
    """
33
    def get_formset(self, request, obj=None, **kwargs):
34
35
36
37
        formset = super().get_formset(request, obj, **kwargs)
        formset.form = disable_fields(request, self.model, obj, formset.form)
        return formset

38

Lincoln Smith's avatar
Lincoln Smith committed
39
class PerFieldPermissionAdmin(admin.ModelAdmin):
40
41
42
43
44
45
46
47
    """
    Extends ModelAdmin by adding a /manage/ url which provides an alternative
    table layout for managing permissions.
    """
    def _get_filter_form_initial(self, request):
        """
        Extracts fields needed to initialise the filter forms from submitted
        data. Uses said forms to verify the submitted data.
Lincoln Smith's avatar
Lincoln Smith committed
48

49
50
51
52
53
54
55
56
57
        Returns a dict of values needed to initialise the filter forms.
        """
        required_fields = [
                'pfp_pfilter-model', 'pfp_pfilter-show_pfps',
                'pfp_rfilter-role_type',
                ]
        initial = {}
        if request.method == 'GET':
            init_data = self.get_changeform_initial_data(request)
58
        elif request.method == 'POST':
59
60
61
62
            init_data = request.POST.copy()
        # Stick the GET or POST data into the form to validate it, and if it
        # validates grab the cleaned data from the required fields which we'll
        # use to populate the non-required fields later on
63
        init_data = {k: v for k, v in init_data.items() if k in required_fields}
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
        init_form = forms.PFPPermFilterForm(data=init_data)
        if init_form.is_bound and init_form.is_valid():
            initial['model'] = init_form.cleaned_data['model']
            initial['show_pfps'] = init_form.cleaned_data['show_pfps']

        init_form = forms.PFPRoleFilterForm(data=init_data)
        if init_form.is_bound and init_form.is_valid():
            initial['role_type'] = init_form.cleaned_data['role_type']

        return initial

    def _get_perm_choices(self, cleaned_data):
        """
        Constructs the list of permissions that will be offered to each
        role in the selection matrix. Expects cleaned data from a
        PFPManagePermsForm.

        Returns a Permission queryset.
        """
        model_ctype = cleaned_data['model']
        perms = [perm.id for perm in cleaned_data['permissions']]

        if cleaned_data['model_fields']:
            fields = cleaned_data['model_fields']

            # If fields and permissions have been selected, then for any model
            # level permissions selected get their linked pfps, and include any
            # directly selected pfps. Otherwise, just get pfps for the
            # fields selected.
            if perms:
                model_perms = Permission.objects.filter(
                        perfieldpermission__isnull=True,
                        id__in=perms,
                        ).values_list('id', flat=True)
                pfp_ids = set(perms).difference(set(model_perms))
                perms_qs = Permission.objects.filter(
                        Q(perfieldpermission__field_name__in=fields,
                            perfieldpermission__model_permission_id__in=model_perms)
                        | Q(id__in=pfp_ids)
                        ).distinct().order_by()
            else:
                perms_qs = Permission.objects.filter(
                        content_type=model_ctype,
                        perfieldpermission__field_name__in=fields
                        ).order_by()
        # If fields aren't set then we use the selected permissions, or all
        # available permissions
        elif cleaned_data['permissions']:
            perms_qs = cleaned_data['permissions']
        elif cleaned_data['show_pfps']:
            perms_qs = Permission.objects.filter(
                    content_type=model_ctype).order_by()
        else:
            perms_qs = Permission.objects.filter(
                    content_type=model_ctype,
                    perfieldpermission__isnull=True,
                    ).order_by()
        return perms_qs

    def _get_perm_select_initial(self, request, clean_data, perms_qs):
        """
        Get info about which permissions roles currently possess so we can
        intialise the selection form. Kind of expensive in terms of queries but
        we shouldn't be doing this often.

        Should split this into getting roles, and creating initial tuple.

        Returns a tuple to pass to the formset generated by
        pfp_perm_select_form_factory(), and a Page object for paginating the
        display of the selected roles.
        """
        role_type = clean_data['role_type']
        role_class = role_type.model_class()
        user_model = get_user_model()
        remote_fields = get_m2m_remote_fields(Permission, role_class)
        if len(remote_fields) != 1:
140
141
            raise ValidationError('The role type selected has no, or multiple relations to the '
                                  'Permissions model. Expected to find one.')
142
143
144
145
146
        else:
            role_related_query = remote_fields[0].name

        initial = []
        all_roles = role_class.objects.all().order_by()
147

148
149
150
151
152
153
        # Paginate list of roles
        paginator = Paginator(all_roles, 25)
        page = request.GET.get('page')
        try:
            roles = paginator.page(page)
        except PageNotAnInteger:
154
            roles = paginator.page(1)
155
156
        except EmptyPage:
            roles = paginator.page(paginator.num_pages)
157

158
159
160
161
162
163
164
165
166
167
168
169
170
        for role in roles:
            perms = perms_qs.filter(**{role_related_query: role}).order_by()
            if role_class == user_model:
                if role.get_full_name():
                    role_name = role.get_full_name()
                else:
                    role_name = role.username
            else:
                role_name = role.name
            initial.append({
                    'role_name': role_name,
                    'role_id': str(role.id),
                    'permissions': perms,
Lincoln Smith's avatar
Lincoln Smith committed
171
                    })
172
173
174
175
176
177
        return initial, roles

    def _process_perm_forms(self, request, clean_data, perm_formset):
        """
        Add and remove permissions based on form submission.

178
179
180
181
        Since it's possible users have been added/removed since the list of users was loaded, some
        forms in the formset may have IDs that don't match with what was loaded when the user last
        accessed the form. Skip the user as it would be a pain to try and match them up to an entry
        in the new list of users.
182
183
184
185
186
187
188
189
190
        """
        if perm_formset.forms:
            perms_offered = perm_formset.forms[0].fields['permissions'].queryset
            role_class = clean_data['role_type'].model_class()
            manager_name = get_manager_name(role_class, Permission)

        for form in perm_formset.forms:
            if form.has_changed() and 'permissions' in form.changed_data:
                if 'role_id' in form.changed_data:
191
192
193
194
195
196
                    messages.warning(
                            request,
                            'Permissions for {} were not updated due to database changes since '
                            'loading the form. Please try again.'.format(
                                form.cleaned_data['role_name']
                                ),
197
198
199
200
201
202
203
204
                            )
                    continue

                role_id = form.cleaned_data['role_id']
                selected_perms = set(form.cleaned_data['permissions'])
                try:
                    role = role_class.objects.get(id=role_id)
                except ObjectDoesNotExist:
205
206
207
208
                    messages.error(
                            request,
                            'Permissions for {} were not updated because the role could not be '
                            'found.'.format(form.cleaned_data['role_name']),
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
                            )
                    continue

                # Get perms to add/remove
                init_perms = set(form.initial['permissions'])
                del_perms = init_perms.difference(
                        form.cleaned_data['permissions'])
                add_perms = selected_perms.difference(init_perms)

                # Process
                perm_manager = getattr(role, manager_name)
                with transaction.atomic():
                    perm_manager.remove(*del_perms)
                    perm_manager.add(*add_perms)

224
225
226
227
228
229
230
231
                messages.success(
                        request,
                        'Permissions for {} were changed. Added: {}. Removed: {}.'.format(
                            form.cleaned_data['role_name'],
                            len(add_perms),
                            len(del_perms),
                            )
                        )
232
233
234
235
236
237
238
239
240
241

    def manage_view(self, request):
        """
        Provide a filterable grid of roles/permissions as an alternative to
        editing each user/role individually.
        """
        if not(request.user.has_perm('perfieldperms.manage_permissions')):
            raise PermissionDenied

        context = {}
242
        template = '{}/perfieldperm_manage.html'.format(
243
244
245
246
247
248
249
250
                self.model._meta.app_label)
        page = None
        initial = self._get_filter_form_initial(request)
        data = request.POST
        perm_filter_form = forms.PFPPermFilterForm(initial=initial, data=data)
        role_filter_form = forms.PFPRoleFilterForm(initial=initial, data=data)

        if ((role_filter_form.is_bound and role_filter_form.is_valid())
251
                and
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
                (perm_filter_form.is_bound and perm_filter_form.is_valid())):
            # Filter forms are valid so see if we have a valid selection form
            clean_data = perm_filter_form.cleaned_data.copy()
            clean_data.update(role_filter_form.cleaned_data)
            perms_qs = self._get_perm_choices(clean_data)
            PermSelectFormSet = forms.pfp_perm_select_form_factory(perms_qs)
            # Generate initial data for formset which will be a list of roles
            # and any permissions they currently have.
            perm_select_initial, page = self._get_perm_select_initial(
                    request,
                    clean_data,
                    perms_qs,
                    )

            if '_save' in request.POST or '_continue' in request.POST:
                perm_formset = PermSelectFormSet(
                        initial=perm_select_initial,
                        data=data,
                        )
                try:
                    if perm_formset.is_bound and perm_formset.is_valid():
                        self._process_perm_forms(request, clean_data, perm_formset)
                except ValidationError:
275
276
                    messages.error(request, 'The form failed to validate, probably due to changes '
                                            'to filter settings.')
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
            else:
                perm_formset = PermSelectFormSet(initial=perm_select_initial)
            context['perm_formset'] = perm_formset

        # Update context with info required by the AdminSite, and the template
        context.update(self.admin_site.each_context(request))
        context.update(dict(
                opts=self.model._meta,
                title='Manage permissions',
                save_as=self.save_as,
                save_as_continue=self.save_as_continue,
                show_save=True,
                show_save_and_continue=True,
                show_save_and_add_another=False,
                show_save_as_new=False,
                perm_filter_form=perm_filter_form,
                role_filter_form=role_filter_form,
                page=page,
                ))
        return TemplateResponse(request, template, context=context)
Lincoln Smith's avatar
Lincoln Smith committed
297
298
299
300
301
302
303
304
305
306
307

    def get_urls(self):
        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)
            wrapper.model_admin = self
            return update_wrapper(wrapper, view)

        info = self.model._meta.app_label, self.model._meta.model_name

        urls = [
308
309
                url(r'^manage/$', wrap(self.manage_view),
                    name='{0[0]}_{0[1]}_manage'.format(info)),
Lincoln Smith's avatar
Lincoln Smith committed
310
311
312
                ]
        return urls + super().get_urls()

313

Lincoln Smith's avatar
Lincoln Smith committed
314
315
admin.site.register(models.PerFieldPermission, PerFieldPermissionAdmin)

316

317
318
319
@admin.register(models.PFPContentType)
class PFPContentTypeAdmin(admin.ModelAdmin):
    form = forms.PFPContentTypesForm
320

Lincoln Smith's avatar
Lincoln Smith committed
321

322
323
324
@admin.register(models.PFPRoleType)
class PFPRoleTypeAdmin(admin.ModelAdmin):
    form = forms.PFPRoleTypesForm