src/ldt/ldt/security/permissionchecker.py
author cavaliet
Wed, 09 Oct 2013 10:14:55 +0200
changeset 1240 a9d953866a50
parent 1191 b6e0b1811723
child 1407 fc9654218d53
permissions -rw-r--r--
Added tag V01.51.05 for changeset 150a76f0f05c

from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from guardian.models import UserObjectPermission, GroupObjectPermission


def check_object_perm_for_user(obj, perm_name, user):
    # If user is admin...
    if user.is_staff:
        return True
    # Guardian has_perm request is REALLY long and not optimized.
    # So we check manually the change_project permission for the user and the user's groups
    # Get necessary datas
    model_name = obj.__class__.__name__.lower()
    content_type = ContentType.objects.get(model=model_name)
    perm = Permission.objects.get(codename=perm_name)
    can_change = False
    # Check for the user
    try:
        uop = UserObjectPermission.objects.get(user=user, content_type=content_type, permission=perm, object_pk=obj.pk)
        if uop:
            can_change = True
    except:
        can_change = False
    # Check for user's groups if necessary
    if not can_change:
        try:
            gop = GroupObjectPermission.objects.filter(group__user=user, content_type=content_type, permission=perm, object_pk=obj.pk)
            if gop and len(gop)>0:
                can_change = True
        except:
            can_change = False
    # End
    return can_change