基于 `Django` 自带的权限系统认证

基于 Django 自带的权限系统认证

  • 创建用户 create_user 方法

    from rest_framework.views import APIView
    from rest_framework.response import Response
    
    class UserRegisterView(APIView):
        '''注册用户'''
        def post(request, *args, **kwargs):
            # 添加用户入库
            user_obj = User.objects.create_user(**request.data)
            # 判断是否添加成功
            if not user_obj:
               return Response({"code":0, "msg":"failure" ,"data":{}}, 200)
            return Response({"code":1,"msg":"success","data":{}}, 200)
    
  • 根据用户名和密码登录

    from rest_framework.views import APIView
    from rest_framework.response import Response
    from django.contrib import auth
    
    class UserLoginView(APIView):
        ''' 用户登录 '''
    
        def post(self, request, *args, **kwargs):
            # 验证用户权限
            auth_obj = auth.authenticate(request, **request.data)
            # 如果有权限则直接登录,并将信息写入session和request.user中
            if auth_obj:
                # 将用户数据写入request.user中和session中
                auth.login(request, auth_obj)
                # 填充载荷
                payload = {
                    "uid": request.user.id
                }
                # 生成 token
                token = jwt_encode(payload)
                # 返回数据
                return Response({"code":1,"msg":"登录成功","data":{"token": token}}, 200)
            # 返回登陆失败数据
            return Response({"code":0, "msg":"用户名或者密码错误" ,"data":{}}, 200)
    
  • 注销登录

    from rest_framework.views import APIView
    from rest_framework.response import Response
    from django.contrib import auth
    
    class UserLogoutView(APIView):
        '''用户注销登录'''
        def post(request, *args, **kwargs):
            auth.logout(request)
            return Response({"code": 1,"msg": "用户登出成功", "data":{}}, 200)
    
  • jwt 编码和解码

    '''
    	安装 pyjwt:  pip install pyjwt
    '''
    
    import jwt, time
    
    SECRET_KEY = "e=-4xbvcg!%0*!d1+a$s(8zb_zljav8gd(mj_v2)@&@!ktpr5("
    
    
    def jwt_encode(raw, expir=7200):
        '''jwt编码'''
        raw['exp'] = int(time.time()) + expir
        return jwt.encode(raw, SECRET_KEY, algorithm="HS256").decode()
    
    
    def jwt_decode(raw):
        '''jwt解码'''
        try:
            return jwt.decode(raw, SECRET_KEY, algorithms=["HS256"])
        except:
            return {}
    
  • 新建中间件

    from django.utils.deprecation import MiddlewareMixin
    from django.http import JsonResponse
    
    class UserCheckAuthMiddleware(MiddlewareMixin):
        '''检查用户登录'''
        
        def process_request(request, *args, **kwargs):
            # 判断请求地址是否在白名单中
            if request.path not in ["login/", "logout/", "register/"]:
                token = request.headers.get("token", "")
                if not token:
                    return JsonResponse({"code": -1, "msg": "缺省token", "data":{}}, 200)
                if not jwt_decode(token):
                    return JsonResponse({"code": -1, "msg": "token已过期", "data":{}}, 200)
                if not request.user.is_active:
                    return JsonResponse({"code": -1, "msg": "用户权限受限,请联系管理员", "data":{}}, 200)
    			return None
            
            
    class ExceptionMiddleware(MiddlewareMixin):
    	'''异常捕获'''
        
        def process_exception(self, request, exception):
            return JsonResponse({
                "code": -1,
                "msg": "服务不可用",
                "detail": str(exception),
                "data": {}
            })
    
  • 常用的方法

    方法名 备注
    create_user 创建用户
    authenticate 登录验证
    login 记录登录状态
    logout 退出用户登录
    is_authenticated 判断用户是否登录
    login_required装饰器 进行登录判断
posted @ 2021-06-09 21:13  巫小诗  阅读(131)  评论(0编辑  收藏  举报