1. bjunix
  2. django-rbac


django-rbac / rbac / utils.py

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,
            owner_id=owner.id, content_type=model_ct, operation=operation)
        permission = RBACPermission.objects.get(owner_ct=owner_ct, owner_id=owner.id,
            object_ct=model_ct, object_id=model.id, 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