auth_backends.py 1.1 KB

12345678910111213141516171819202122232425262728
  1. from django.conf import settings
  2. from django.contrib.auth.backends import ModelBackend
  3. class ViewExemptModelBackend(ModelBackend):
  4. """
  5. Custom implementation of Django's stock ModelBackend which allows for the exemption of arbitrary models from view
  6. permission enforcement.
  7. """
  8. def has_perm(self, user_obj, perm, obj=None):
  9. # If this is a view permission, check whether the model has been exempted from enforcement
  10. try:
  11. app, codename = perm.split('.')
  12. action, model = codename.split('_')
  13. if action == 'view':
  14. if (
  15. # All models are exempt from view permission enforcement
  16. '*' in settings.EXEMPT_VIEW_PERMISSIONS
  17. ) or (
  18. # This specific model is exempt from view permission enforcement
  19. '{}.{}'.format(app, model) in settings.EXEMPT_VIEW_PERMISSIONS
  20. ):
  21. return True
  22. except ValueError:
  23. pass
  24. return super().has_perm(user_obj, perm, obj)