认证组件

简介

只有认证通过的用户才能访问指定的url地址,比如:查询课程信息,需要登录之后才能查看,没有登录,就不能查看,这时候需要用到认证组件

局部使用

# models层

class User(models.Model):
    username=models.CharField(max_length=32)
    password=models.CharField(max_length=32)
    user_type=models.IntegerField(choices=((1,'超级用户'),(2,'普通用户'),(3,'二笔用户')))

class UserToken(models.Model):
    user=models.OneToOneField(to='User')
    token=models.CharField(max_length=64)
# 新建认证类

from rest_framework.authentication import BaseAuthentication
class TokenAuth():
    def authenticate(self, request):
        token = request.GET.get('token')
        token_obj = models.UserToken.objects.filter(token=token).first()
        if token_obj:
            return
        else:
            raise AuthenticationFailed('认证失败')
    def authenticate_header(self,request):
        pass
# view层

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()

class Login(APIView):
    def post(self,request,*args,**kwargs):
        response={
            'status': 100,
            'msg': '成功'
        }
        try:
            name = request.data.get('name')
            pwd = request.data.get('pwd')
            user = models.User.objects.filter(
                name=name, pwd=pwd
            ).first()
            if user:
                token = get_random(name)
                # 使用update_or_create,妙处
                models.Token.objects.update_or_create(
                    user, defaults={'token': token}
                )
                response['msg']='登录成功'
                response['token']=token
            else:
                response['msg']='用户名或密码'
        except Exception as e:
            response['msg']=str(e)

        return Response(response)

class Course(APIView):
    # 认证类
    authentication_classes = [TokenAuthentication,]

    def get(self,request):
        return HttpResponse('get')

    def post(self,request):
        return HttpResponse('post')

源代码流程

见认证组件源代码分析

posted @ 2019-03-28 08:44  kongpan  阅读(151)  评论(0编辑  收藏  举报