Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#2023] Implemented Category/Product admin access based on auth.Group #967

Merged
merged 4 commits into from
Feb 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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, 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 @@ -212,6 +211,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 @@ -469,6 +469,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
37 changes: 37 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,47 @@ class CategoryAdmin(
},
),
)
readonly_fields = [
"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_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
58 changes: 57 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,47 @@ class Meta:
fields = "__all__"
widgets = {"content": CKEditorWidget}

categories = forms.ModelMultipleChoiceField(
stevenbal marked this conversation as resolved.
Show resolved Hide resolved
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 clean(self):
cleaned_data = super().clean()
if len(cleaned_data["categories"]) == 0:
self.add_error("categories", _("At least one category is required"))
return cleaned_data

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 +91,6 @@ class ProductAdmin(ImportExportMixin, admin.ModelAdmin):
list_editable = ("published",)
date_hierarchy = "created_on"
autocomplete_fields = (
"categories",
"related_products",
"tags",
"organizations",
Expand All @@ -72,6 +114,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 +139,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 its 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 its products"
),
related_name="managed_categories",
)

objects = CategoryPublishedQueryset.as_manager()

class Meta:
Expand Down
Loading
Loading