|
| 1 | +"""Signal handlers for the authorization framework. |
| 2 | +
|
| 3 | +These handlers ensure proper cleanup and consistency when models are deleted. |
| 4 | +""" |
| 5 | + |
| 6 | +from casbin_adapter.models import CasbinRule |
| 7 | +from django.db.models.signals import post_delete |
| 8 | +from django.dispatch import receiver |
| 9 | + |
| 10 | +from openedx_authz.models.core import ExtendedCasbinRule |
| 11 | + |
| 12 | +import logging |
| 13 | + |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | + |
| 17 | +@receiver(post_delete, sender=ExtendedCasbinRule) |
| 18 | +def delete_casbin_rule_on_extended_rule_deletion(sender, instance, **kwargs): |
| 19 | + """Delete the companion CasbinRule after its ExtendedCasbinRule disappears. |
| 20 | +
|
| 21 | + The handler keeps authorization data symmetric with three common flows: |
| 22 | + - Direct ExtendedCasbinRule deletes (API/UI) trigger removal of the linked CasbinRule. |
| 23 | + - Cascades from `Scope` or `Subject` deletions clear their ExtendedCasbinRule rows and, via this handler, the matching CasbinRule entries. |
| 24 | + - Cascades initiated from the CasbinRule side (enforcer cleanups) leave the query as a no-op because the row is already gone. |
| 25 | +
|
| 26 | + Running on ``post_delete`` ensures database cascades complete before the cleanup runs, so |
| 27 | + enforcer-driven deletions no longer raise false errors. |
| 28 | +
|
| 29 | + Args: |
| 30 | + sender: The model class (ExtendedCasbinRule). |
| 31 | + instance: The ExtendedCasbinRule instance being deleted. |
| 32 | + **kwargs: Additional keyword arguments from the signal. |
| 33 | + """ |
| 34 | + try: |
| 35 | + # Rely on delete() being idempotent; returns 0 rows if the CasbinRule was |
| 36 | + # already removed (for example, because it triggered this signal). |
| 37 | + CasbinRule.objects.filter(id=instance.casbin_rule_id).delete() |
| 38 | + except Exception as exc: |
| 39 | + # Log but don't raise - we don't want to break the deletion of |
| 40 | + # ExtendedCasbinRule if something goes wrong while deleting the CasbinRule. |
| 41 | + logger.exception( |
| 42 | + "Error deleting CasbinRule %s during ExtendedCasbinRule cleanup", |
| 43 | + instance.casbin_rule_id, |
| 44 | + exc_info=exc, |
| 45 | + ) |
0 commit comments