django-rbac / rbac /

from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist

from rbac.models import RBACOperation
from rbac.models import RBACPermission, RBACGenericPermission

def get_permission(owner, model, operation, generic):
    owner_ct = ContentType.objects.get_for_model(owner)
    model_ct = ContentType.objects.get_for_model(model)
    # TODO: remove generic param, if model is an instance then do an
    # RBACPermission search, if it is a Model class do a RBACGenericPermission instead
    if generic:
        permission = RBACGenericPermission.objects.get(owner_ct=owner_ct,
  , content_type=model_ct, operation=operation)
        permission = RBACPermission.objects.get(owner_ct=owner_ct,,
            object_ct=model_ct,, operation=operation)
    return permission

def rbac_permission(roles, owner, model, operation_str, generic=True):
    # TODO: change order of params to match manager methods
    # TODO: remove generic param
    # TODO: roles param could be a list/queryset or a single model instance
    operation = RBACOperation.objects.get(name=operation_str)
        permission = get_permission(owner, model, operation, generic)
    # If permission does not exist, authorization is not allowed
    except ObjectDoesNotExist:
        return False
        for role in permission.roles.all():
            if role in roles:
                return True
        return False