DRF认证组件流程分析

视图函数中加上认证功能,流程见下图

import hashlib
import time
def get_random(name):
    md = hashlib.md5()
    md.update(bytes(str(time.time()),encoding='utf-8'))
    md.update(bytes(name,encoding='utf-8'))
    return md.hexdigest()
from rest_framework.views import APIView
class Login(APIView):
    authentication_classes = [AuthLogin]
    def post(self, request, *args, **kwargs):
        response = {'status': 100, 'msg': None}
        name = request.data.get('name')
        pwd = request.data.get('pwd')
        user = models.User.objects.filter(name=name, password=pwd).first()
        if user:
            response['msg'] = '登陆成功'
            # 随机字符串可以是用户名加当前时间生成的mds
            token = get_random(name)
            # 如果有记录,就只需要更新,不需要重新插入
            # models.UserToken.objects.create(token=token,user=user)
            # 查询 更新
            # user_agent
            models.UserToken.objects.update_or_create(user=user, defaults={'token': token})
            response['token'] = token
        else:
            response['status'] = 101
            response['msg'] = '用户名或密码错误'
        return Response(response)
from rest_framework.permissions import BasePermission
from rest_framework.exceptions import NotAuthenticated
from app01 import models
# BaseAuthentication
class AuthLogin(BaseAuthentication):
    def authenticate(self, request):
        # 封装后的request
        token = request.GET.get('token')
        # print(token)
        ret = models.UserToken.objects.filter(token=token).first()
        if ret:
            return ret.user,token
        else:
            raise NotAuthenticated('您没有登陆')

在def initial(self, request, *args, **kwargs):函数中找到认证功能

流程总结:

  • dispatch 方法里self.initial里面有个认证组件self.perform_authentication(request)
  • 到了APIview 返回了request.user (封装后的Request)
  • 去request类里找user方法,被包装成了属性,里面执行了一个方法,self._authticate方法
  • self._authticate方法里从自己的authenticators一个一个的取东西,authenticators
  • 于是查看authenticators,是初始化的时候init传过来了,self.authenticators = authenticators or()
  • 到dispatch里找初始化的时候,也就是APIView的initialize_request方法传了self.authenticators,里面是一个get_authenticators的方法
  • self.authentication_classes 是[类1,类2,类3]一个一个取,加括号执行。生成一个一个对象.最后返回到前面的Request的_authenticate方法
  • 拿到对象之后,执行user_auth_tuple = authenticator.authenticate(self)
  • 注意authenticate是需要在视图函数中自己定义的,self.user, self.auth = user_auth_tuple返回两个值,流程结束。

猜你喜欢

转载自www.cnblogs.com/wanlei/p/10426844.html