如何使用tastypi中的自定义用户类型限制对资源的GET、POST访问

2024-09-19 23:36:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经为addnewusertype字段扩展了Django默认的“User”模型。用户类型类别包括用户管理员查看者。 我想使用tastypi实现RESTapi,并根据用户类型授予访问该api的权限。 例如,管理员用户可以完全访问此API,用户可以查看所有字段,但只能更新自己的帐户,查看器无权访问此API。你知道吗

你知道吗api.py公司你知道吗

    class UserResource(ModelResource):
        class Meta:
            queryset = CustomUser.objects.all()
            resource_name = 'user'
            allowed_methods = ['get','post']
            filtering = {"id": ALL}
            excludes = ['is_staff','password','is_superuser','id','is_active','date_joined']
            authentication =  BasicAuthentication()

处理这个问题的最佳方法是什么?


Tags: django用户模型apirestapiid类型is
1条回答
网友
1楼 · 发布于 2024-09-19 23:36:31

首先,编写自己的身份验证类。在该类中,检查用户是否为查看器。如果是,则返回False。你知道吗

class MyAuthentication(BasicAuthentication):
    def is_authenticated(self, request, **kwargs):
        is_authenticated = super(MyAuthentication, self).is_authenticated(request, **kwargs)
        if not is_authenticated:
            return False
        return request.user.user_type_category != 'viewer'

其次,编写自己的授权类。在这个类中,覆盖函数[create|update|delete]_[list|detail]并在create/delete函数中检查user是否为user。如果是,则引发异常(详细信息)或返回[](列表中)。在更新中检查用户是否更新自己。如果否,则引发异常或返回[]。你知道吗

class MyAuthorization(DjangoAuthorization):
    def create_detail(self, object_list, bundle):
        super(MyAuthorization, self).create_detail(object_list, bundle)
        if bundle.request.user.user_type_category != 'admin':
            raise Unauthorized("You are not allowed to create that resource.")
        return True

    def create_list(self, object_list, bundle):
        if bundle.request.user.user_type_category != 'admin':
            return []
        return super(MyAuthorization, self).create_list(object_list, bundle)

    def delete_detail(self, object_list, bundle):
        super(MyAuthorization, self).delete_detail(object_list, bundle)
        if bundle.request.user.user_type_category != 'admin':
            raise Unauthorized("You are not allowed to delete that resource.")
        return True

    def delete_list(self, object_list, bundle):
        if bundle.request.user.user_type_category != 'admin':
            return []
        return super(MyAuthorization, self).delete_list(object_list, bundle)

    def update_detail(self, object_list, bundle):
        super(MyAuthorization, self).delete_detail(object_list, bundle)
        if bundle.request.user != bundle.obj:
            raise Unauthorized("You are not allowed to update that resource.")
        return True

    def update_list(self, object_list, bundle):
        object_list = super(MyAuthorization, self).update_list(object_list, bundle)
        if object_list.count() == object_list.filter(pk=bundle.obj.pk).count():
            return object_list
        return []

相关问题 更多 >