django 使用规则的DRF ViewSet操作授权

f4t66c6m  于 2023-03-20  发布在  Go
关注(0)|答案(1)|浏览(98)

考虑以下模型

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)

以及以下视图集

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()操作限制为仅用户类型为TEACHER的用户?

p4tfgftt

p4tfgftt1#

如果要自动应用模型中定义的权限,可以使用
在你们课程中,模型是这样的

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)

相关问题