补充:代码混淆

想让别人破解你的项目难度大,恶心别人,就要先把自己的代码变得恶心,让别人看不懂,这些混淆工具可以把代码编程这样:

除非是逆向工程师,常人根本看不懂。

用户权限

功能分析

现在规定只有超级管理员可以查看所有用户信息,其他用户访问时被拒绝。

  • 用户权限

    • BasePermission

      • has_permission

        • 是否具有权限
        • true拥有权限
        • false未拥有权限
  • 用户认证和权限

    • 直接配置在视图函数上就ok了


这里就用到了permission_classes方法.
这里默认权限是:

    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ],

允许任何人:

class AllowAny(BasePermission):
    """
    Allow any access.
    This isn't strictly required, since you could use an empty
    permission_classes list, but it's useful because it makes the intention
    more explicit.
    """

    def has_permission(self, request, view):
        return True

实现权限

新建permission

查看APIView的dispatch中的initial中的self.check_permissions(request)函数:

    def check_permissions(self, request):
        """
        Check if the request should be permitted.
        Raises an appropriate exception if the request is not permitted.
        """
        for permission in self.get_permissions():  # 遍历权限类
            if not permission.has_permission(request, self): # 没有权限就抛出拒绝
                self.permission_denied(
                    request,
                    message=getattr(permission, 'message', None),
                    code=getattr(permission, 'code', None)
                )

所以permissions.py中只需要重写has_permission方法,有权限就return True否则返回False。

新建permissions.py:

from rest_framework.permissions import BasePermission

from UserAuthAndPermission.models import UserModel


class IsSuperUser(BasePermission):

    def has_permission(self, request, view):
        if request.method =='GET':
            if isinstance(request.user, UserModel):
                # 是超级管理员就返回
                return request.user.is_super
            return False
        return True

测试

首先登陆普通用户获取token:

使用普通用户的token发起get请求:

接着使用超级管理员的token发起get请求:

成功实现权限功能。

总结

这样设计用户模块,将功能拆分开,方便维护,并且全局都可以使用,不需要重复编写代码。

最后修改:2024 年 03 月 13 日
如果觉得我的文章对你有用,请随意赞赏