暫無描述

signals.py 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from __future__ import annotations
  2. from django.db.models.signals import post_save
  3. from django.dispatch import receiver
  4. from django.contrib.auth.models import Group
  5. from .models import UserProfile
  6. ROLE_GROUP_MAP = {
  7. UserProfile.ROLE_OWNER: "owner",
  8. UserProfile.ROLE_MANAGER: "manager",
  9. UserProfile.ROLE_DRIVER: "driver",
  10. UserProfile.ROLE_CUSTOMER: "customer",
  11. UserProfile.ROLE_AUDITOR: "auditor",
  12. }
  13. MANAGED_GROUPS = set(ROLE_GROUP_MAP.values())
  14. @receiver(post_save, sender=UserProfile)
  15. def sync_profile_role_to_groups(sender, instance: UserProfile, created: bool, **kwargs):
  16. """Keep Django Group membership in sync with the profile role.
  17. - Removes the user from managed role groups (owner/manager/driver/customer/auditor)
  18. - Adds the user to the group mapped from the current role
  19. - Lazily creates the Group if missing
  20. """
  21. user = instance.user
  22. if user is None or not getattr(user, "pk", None):
  23. return
  24. # Remove from managed groups first (do not touch other unrelated groups)
  25. current_managed = user.groups.filter(name__in=MANAGED_GROUPS)
  26. if current_managed.exists():
  27. user.groups.remove(*current_managed)
  28. # Add target group for role
  29. group_name = ROLE_GROUP_MAP.get(instance.role)
  30. if not group_name:
  31. return
  32. group, _ = Group.objects.get_or_create(name=group_name)
  33. user.groups.add(group)