有规则的DRF ViewSet操作授权

DRF ViewSet operation authorization with rules

考虑以下模型

class MyUser(AbstractBaseUser):
    ADMIN = 0
    TEACHER = 100
    STUDENT = 200
    UNSPECIFIED = 256

    USER_TYPE_CHOICES = (
        (ADMIN, 'admin'),
        (TEACHER, 'teacher'),
        (STUDENT, 'student'),
        (UNSPECIFIED, 'unspecified')
    )
    ...
    user_type = models.IntegerField(db_column='userType', choices=USER_TYPE_CHOICES, blank=True, default=UNSPECIFIED)

还有下面的ViewSet

class CourseViewSet(ViewSet):

    def create(self, request):
        serializer = CourseSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)

使用django-rules,如何将CourseViewSet 中的create() 操作仅限于user_type TEACHER 的用户?

如果您想自动应用模型中定义的权限,您可以使用

在你的课程模型中是这样的

from rules import predicates

@predicates.predicate()
def check_teacher(user):
    if not hasattr(user, 'user_type'):
        return False

    if user.user_type == 'teacher':
        return True

    return False


class Course(models.Model):
    ....
    class Meta:
        rules_permissions = {
            "add": check_teacher,
            "read": rules.always_allow,
        }

和您的观点

from rules.contrib.rest_framework import AutoPermissionViewSetMixin

class CourseViewSet(AutoPermissionViewSetMixin, viewsets.ViewSet):
    def get_queryset(self):
        return Course.objects.all()

    def create(self, request):
        serializer = CourseSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)