Skip to content

Commit

Permalink
[#2023] Implemented Category/Product admin access based on auth.Group
Browse files Browse the repository at this point in the history
  • Loading branch information
Bart van der Schoor committed Jan 23, 2024
1 parent c63452b commit 4b49cd4
Show file tree
Hide file tree
Showing 10 changed files with 408 additions and 9 deletions.
36 changes: 34 additions & 2 deletions src/open_inwoner/accounts/admin.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from django.contrib import admin, messages
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.admin import GroupAdmin, UserAdmin
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from django.contrib.auth.models import Group
from django.forms import ValidationError
from django.http.request import HttpRequest
from django.urls import reverse, reverse_lazy
from django.utils.html import format_html
from django.utils.html import format_html, format_html_join
from django.utils.translation import ngettext, ugettext_lazy as _

from image_cropping import ImageCroppingMixin
Expand All @@ -13,6 +14,7 @@
from open_inwoner.utils.mixins import UUIDAdminFirstInOrder

from .choices import ContactTypeChoices
from .forms import GroupAdminForm
from .models import Action, Appointment, Document, Invite, Message, User


Expand Down Expand Up @@ -167,6 +169,36 @@ class _UserAdmin(ImageCroppingMixin, UserAdmin):
)


admin.site.unregister(Group)


@admin.register(Group)
class _GroupAdmin(GroupAdmin):
form = GroupAdminForm

list_display = [
"name",
"get_categories",
]
filter_horizontal = [
"permissions",
]
list_filter = ["managed_categories", "permissions"]

fieldsets = (
(None, {"fields": ("name", "permissions")}),
(
_("Additional permissions"),
{"fields": ("managed_categories",)},
),
)

def get_categories(self, obj):
return ", ".join(g.name for g in obj.managed_categories.all())

get_categories.short_description = _("Admin categories")


@admin.register(Action)
class ActionAdmin(
ReadOnlyFileMixin, UUIDAdminFirstInOrder, PrivateMediaMixin, admin.ModelAdmin
Expand Down
34 changes: 31 additions & 3 deletions src/open_inwoner/accounts/forms.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
from typing import Optional

from django import forms
from django.conf import settings
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.contrib.auth import authenticate
from django.contrib.auth.forms import PasswordResetForm
from django.contrib.auth.models import Group
from django.core.exceptions import ValidationError
from django.core.mail import EmailMultiAlternatives
from django.db.models import Q
from django.template import loader
from django.utils.translation import ugettext_lazy as _

Expand Down Expand Up @@ -213,6 +212,35 @@ def __init__(self, user, *args, **kwargs):
del self.fields[field_name]


class GroupAdminForm(forms.ModelForm):
"""
Add the ability to add/remove 'managed_categories' to the GroupAdmin.
"""

managed_categories = forms.ModelMultipleChoiceField(
label=_("Restricted PDC categories"),
queryset=Category.objects.all(),
required=False,
widget=FilteredSelectMultiple(verbose_name=_("Category"), is_stacked=False),
)

class Meta:
model = Group
fields = ("name", "permissions")

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

if self.instance and self.instance.pk:
self.fields[
"managed_categories"
].initial = self.instance.managed_categories.all()

def _save_m2m(self):
super()._save_m2m()
self.instance.managed_categories.set(self.cleaned_data["managed_categories"])


class CustomPasswordResetForm(PasswordResetForm):
def get_users(self, email):
users = super().get_users(email)
Expand Down
14 changes: 12 additions & 2 deletions src/open_inwoner/accounts/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
from uuid import uuid4

from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.contrib.auth.models import AbstractBaseUser, Group, PermissionsMixin
from django.contrib.contenttypes.fields import GenericRelation
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import CheckConstraint, Q, UniqueConstraint
from django.db.models import Q, UniqueConstraint
from django.urls import reverse
from django.utils import timezone
from django.utils.crypto import get_random_string
Expand Down Expand Up @@ -482,6 +482,16 @@ def is_digid_user_with_brp(self) -> bool:
def is_eherkenning_user(self) -> bool:
return self.login_type == LoginTypeChoices.eherkenning

def has_group_managed_categories(self) -> bool:
from ..pdc.models import Category

return Category.objects.filter(access_groups__user=self).exists()

def get_group_managed_categories(self):
from ..pdc.models import Category

return Category.objects.filter(access_groups__user=self)


class Document(models.Model):
uuid = models.UUIDField(
Expand Down
7 changes: 7 additions & 0 deletions src/open_inwoner/accounts/tests/factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@
from open_inwoner.accounts.choices import LoginTypeChoices


class GroupFactory(factory.django.DjangoModelFactory):
class Meta:
model = "auth.Group"

name = factory.Faker("word")


@factory.django.mute_signals(pre_save, post_save)
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
Expand Down
46 changes: 46 additions & 0 deletions src/open_inwoner/pdc/admin/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ class CategoryAdmin(
"visible_for_anonymous",
"visible_for_companies",
"visible_for_citizens",
"get_access_groups_label",
)
list_editable = (
"highlighted",
Expand Down Expand Up @@ -176,6 +177,7 @@ class CategoryAdmin(
"visible_for_anonymous",
"visible_for_companies",
"visible_for_citizens",
"access_groups",
),
},
),
Expand All @@ -189,12 +191,56 @@ class CategoryAdmin(
},
),
)
filter_horizontal = [
"access_groups",
]

list_filter = [
"published",
"visible_for_anonymous",
"visible_for_companies",
"visible_for_citizens",
"access_groups",
]

# import-export
import_template_name = "admin/category_import.html"
resource_class = CategoryImportResource
formats = [base_formats.XLSX, base_formats.CSV]

def get_fields(self, request, obj=None):
fields = list(super().get_fields(request, obj=obj))
if not request.user.has_perm("auth.change_group"):
try:
fields.remove("access_groups")
except ValueError:
pass
return fields

def get_inlines(self, request, obj):
inlines = list(super().get_inlines(request, obj))

# disable product management if we have restrictions
if request.user.has_group_managed_categories():
try:
inlines.remove(CategoryProductInline)
except ValueError:
pass

return inlines

def get_queryset(self, request):
qs = super().get_queryset(request)
categories = request.user.get_group_managed_categories()
if categories:
qs = qs.filter(id__in=categories)
return qs

def get_access_groups_label(self, obj):
return ", ".join(g.name for g in obj.access_groups.all())

get_access_groups_label.short_description = _("Allowed admin groups")

def get_export_resource_class(self):
return CategoryExportResource

Expand Down
53 changes: 52 additions & 1 deletion src/open_inwoner/pdc/admin/product.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from django import forms
from django.contrib import admin
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.utils.translation import gettext as _

from import_export.admin import ImportExportMixin
Expand All @@ -11,6 +12,7 @@
from open_inwoner.utils.mixins import UUIDAdminFirstInOrder

from ..models import (
Category,
Product,
ProductCondition,
ProductContact,
Expand Down Expand Up @@ -40,6 +42,41 @@ class Meta:
fields = "__all__"
widgets = {"content": CKEditorWidget}

categories = forms.ModelMultipleChoiceField(
label=_("Allowed admin categories"),
queryset=Category.objects.all(),
required=False,
widget=FilteredSelectMultiple(verbose_name=_("Category"), is_stacked=False),
)

def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
super().__init__(*args, **kwargs)

# we only want to add/remove Categories we have access to and keep te rest
user_categories = self.request.user.get_group_managed_categories()
if user_categories:
self.fields["categories"].queryset = user_categories
if self.instance and self.instance.pk:
self.fields[
"categories"
].initial = self.instance.categories.intersection(user_categories)

def _save_m2m(self):
# remember this before we run regular _save_m2m()
current = set(self.instance.categories.all())

super()._save_m2m()

# we only want to add/remove Categories we have access to and keep the ones we don't,
# so do some set operations to figure it out
managed = set(self.request.user.get_group_managed_categories())
if managed:
want_managed = managed & set(self.cleaned_data["categories"])
keep_not_ours = current - managed
combined = keep_not_ours | want_managed
self.instance.categories.set(combined)


@admin.register(Product)
class ProductAdmin(ImportExportMixin, admin.ModelAdmin):
Expand All @@ -48,7 +85,7 @@ class ProductAdmin(ImportExportMixin, admin.ModelAdmin):
list_editable = ("published",)
date_hierarchy = "created_on"
autocomplete_fields = (
"categories",
# "categories",
"related_products",
"tags",
"organizations",
Expand All @@ -72,6 +109,17 @@ class ProductAdmin(ImportExportMixin, admin.ModelAdmin):
import_template_name = "admin/product_import.html"
formats = [base_formats.XLSX, base_formats.CSV]

def get_form(self, request, obj=None, change=False, **kwargs):
# workaround to get the request in the Modelform
Form = super().get_form(request, obj=obj, change=change, **kwargs)

class RequestForm(Form):
def __new__(cls, *args, **kwargs):
kwargs["request"] = request
return Form(*args, **kwargs)

return RequestForm

def get_export_resource_class(self):
return ProductExportResource

Expand All @@ -86,6 +134,9 @@ def export_action(self, request, *args, **kwargs):

def get_queryset(self, request):
qs = super().get_queryset(request)
categories = request.user.get_group_managed_categories()
if categories:
qs = qs.filter(categories__in=categories)
return qs.prefetch_related("links", "locations", "contacts")

def display_categories(self, obj):
Expand Down
25 changes: 25 additions & 0 deletions src/open_inwoner/pdc/migrations/0066_category_access_groups.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Generated by Django 3.2.23 on 2024-01-23 10:32

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("auth", "0012_alter_user_first_name_max_length"),
("pdc", "0065_auto_20240112_1046"),
]

operations = [
migrations.AddField(
model_name="category",
name="access_groups",
field=models.ManyToManyField(
blank=True,
help_text="If set only users belonging to this group can edit this category and it's products",
related_name="managed_categories",
to="auth.Group",
verbose_name="Restrict to admin groups",
),
),
]
10 changes: 10 additions & 0 deletions src/open_inwoner/pdc/models/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,16 @@ class Category(MP_Node):
),
)

access_groups = models.ManyToManyField(
"auth.Group",
verbose_name=_("Restrict to admin groups"),
blank=True,
help_text=_(
"If set only users belonging to this group can edit this category and it's products"
),
related_name="managed_categories",
)

objects = CategoryPublishedQueryset.as_manager()

class Meta:
Expand Down
Loading

0 comments on commit 4b49cd4

Please sign in to comment.