django-rest-framework搭建平台实战教程三:接口编写及权限校验(前后端分离)

自定义权限校验

重写添加用户接口增加groups字段

class DUserViewSet(CustomViewSet):
    ...

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        serializer.instance.create_user_id = request.user.id
        serializer.instance.set_password(request.data['password'])
        serializer.instance.groups.set(request.data['roles'])
        serializer.instance.save()
        headers = self.get_success_headers(serializer.data)
        return Response({
            "code": 0,
            "data": serializer.data
        },headers=headers)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        serializer.instance.set_password(request.data['password'])
        serializer.instance.groups.set(request.data['roles'])
        serializer.instance.save()
        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response({
            "code": 0,
            "data": serializer.data
        })

请求参数加groups:[id...]就能关联到用户组

请求/permission/接口能查到所有权限id,和codename

1. 视图类校验权限

由于Django REST framework的增删改查接口添加permissions.DjangoModelPermissions来判断用户是否已经拥有相应权限。

class DUserViewSet(CustomViewSet):
    ...
    permission_classes = [permissions.IsAuthenticated,permissions.DjangoModelPermissions]

此时请求新增用户和删除用户会提示用户无权限You do not have permission to perform this action.

group视图添加set_permissions方法

...
@action(methods=['POST'],detail=True,permission_classes=[permissions.IsAuthenticated])
    def set_permissions(self,request: Request, pk=None):
        if request.user.has_perm("auth.change_permission"):
            group = Group.objects.filter(id=pk).first()
            group.permissions.set(request.data["permissions"])
            return Response({
            "code": 0,
            "msg": "操作成功"
        })
        else:
            raise PermissionDenied

根据/permission/接口查到权限id赋予用户接口增删改查权限

 再次添加用户接口就能正常响应。

2. 自定义视图校验权限

添加的自定义视图也可以给权限,使用@permission_required这个装饰器。设置了raise_exception=True, 会直接返回403无权限的错误,而不会跳转到登录页面。

views.py添加info接口

...
@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])def info(request: Request):
    user: User = request.user
    response = Response({
        "code": 0,"data": {
            "id": user.id,
            "username": user.username,
            "nickName": user.username
        }
    })
    return response

urls.py加入路由

path('user/info',views.info),

请求user/info接口就能返回用户信息

至此django用户管理及权限验证的后台接口基本后端框架就完成了,还有一些细节需要自己去改进,然后就是选择前端框架编写前端页面。

posted @ 2023-11-02 10:23  紧肛胡撸娃  阅读(185)  评论(0编辑  收藏  举报