from django.contrib.auth.backends import BaseBackend
from django.contrib.auth.models import Permission

from topdownrbac.models import UserPermission


class RestrictedObjectBackend(BaseBackend):

    def has_perm(self, user_obj, perm, obj=None):

        if obj is None:
            return False

        perm = Permission.objects.get(codename=perm)

        return UserPermission.objects.filter(user=user_obj, perm=perm, restricted_object=obj).exists()
