def has_perm(self, perm, obj=None): # determine whether a user or a group has provided permission if hasattr(self.instance, 'is_superuser') and self.instance.is_superuser: return True if perm is None: return False try: self.get_perm(perm, obj) except get_perm_model().DoesNotExist: return False return True
def get_perm(perm, obj=None): perm_model = get_perm_model() if perm is None or isinstance(perm, perm_model): return perm perm_kwargs = perm_model.get_perm_kwargs(perm, obj) try: perm = perm_model.objects.get(**perm_kwargs) except perm_model.DoesNotExist: if settings.PERM_AUTO_CREATE: # create the required perm if it doesn't exist and is supposed to be created perm = perm_model.objects.create(**perm_kwargs) else: # check if a wildcard permission exists instead perm_kwargs['codename'] = enums.PERM_CODENAME_WILDCARD perm = perm_model.objects.get(**perm_kwargs) return perm
from django.apps import apps from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from fperms import get_perm_model from fperms.utils import get_content_type Perm = get_perm_model() def get_perm_from_permission_codename(permission_codename): # get permission object based on django hard-coded permission codename app_label, model_action = permission_codename.split('.', 1) action, model_name = model_action.split('_') model = apps.get_model(app_label, model_name) return Perm.objects.get( content_type=get_content_type(model), codename=action, object_id=None, field_name=None, ) class PermBackend(ModelBackend): # authentication backend, mostly for compatibility with django admin site def has_perm(self, user_obj, perm, obj=None): if user_obj.is_superuser:
def _create_from_str(self, perm, obj): # create a perm instance based on perm kwargs perm_kwargs = get_perm_model().get_perm_kwargs(perm, obj) return self.create(**perm_kwargs)
def get_from_str(self, perm, obj=None): # get a perm instance based on perm kwargs perm_kwargs = get_perm_model().get_perm_kwargs(perm, obj) return self.get(**perm_kwargs)