Skip to content

Commit

Permalink
Merge pull request #1371 from Amsterdam/task/add-custom-permission-fo…
Browse files Browse the repository at this point in the history
…r-storing-18next-translation-file

Introduce CustomPermission abstract class and sync_custom_permission function + custom i18next permission
  • Loading branch information
vanbuiten authored Sep 18, 2023
2 parents b40708e + ea1be44 commit 5564c58
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
1 change: 1 addition & 0 deletions app/signals/apps/signals/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ class SignalsConfig(AppConfig):
def ready(self):
# Import Django signals to connect receiver functions.
import signals.apps.signals.signal_receivers # noqa
import signals.apps.signals.models.permission # noqa
48 changes: 48 additions & 0 deletions app/signals/apps/signals/models/permission.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# SPDX-License-Identifier: MPL-2.0
# Copyright (C) 2023 Gemeente Amsterdam
import logging

from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models.signals import post_migrate
from django.dispatch import receiver

logger = logging.getLogger(__name__)


class CustomPermission(models.Model):
"""
An abstract class for creating custom permissions that do not belong to any existing model.
Django's built-in auth Permissions require a ContentType association.
"""
class Meta:
abstract = True


@receiver(post_migrate)
def sync_custom_permissions(sender, **kwargs):
"""
Synchronize custom permissions after a migration.
This function listens to the post_migrate signal in Django and creates custom permissions
if they do not already exist.
These custom permissions are associated with the CustomPermission model.
Args:
sender: The sender of the signal (usually the app with the migrations).
**kwargs: Additional keyword arguments provided by the signal.
"""
content_type = ContentType.objects.get_for_model(CustomPermission, for_concrete_model=False)

custom_permissions = [
# Custom permission to allow users to create i18next translation files.
('add_i18next_translation_file', 'Can create i18next translation file')
]

for codename, name in custom_permissions:
if not Permission.objects.filter(name=name, codename=codename, content_type=content_type).exists():
logger.info(f'Creating custom permission "{codename}" with name "{name}"')
Permission.objects.create(name=name, codename=codename, content_type=content_type)

0 comments on commit 5564c58

Please sign in to comment.