1

Restframework 认证authentication 组件实例-1

 

1. 创建用户表和 token表

class User(models.Model):
    user =models.CharField(max_length=32)
    pwd =models.CharField(max_length=32)
    type=((1,"VIP"),(2,"SVIP"),(1,"SSVIP"))
    user_type = models.IntegerField(choices=type)


class UserToken(models.Model):
    user= models.OneToOneField("User")
    token =models.CharField(max_length=128)

 

2.创建登录类

from app01.models import User,UserToken

class LoginView(APIView):
    """
    1000:成功
    1001: 用户名和密码错误
    1002:异常错误
    """
    def post(self,request):
        response = {"code": 100, "msg": None, "user": None}
        try:
            print(request.data)
            user= request.data.get("user")
            pwd =request.data.get("pwd")

            user =User.objects.filter(user=user,pwd=pwd).first()

            import uuid
            random_str =uuid.uuid4()

            if user:
                response["user"] =user.user
                UserToken.objects.update_or_create(user =user,defaults={"token":random_str})
                response["user"] =user.user
                response["token"] =random_str
            else:
                response["code"]=1001
                response["msg"]="密码错误"

        except Exception as e:
             response["code"] =1002
             response["msg"] =str(e)

        return Response(response)

 

3.设置认证类逻辑.

from app01.models import UserToken
from rest_framework.exceptions import AuthenticationFailed

from rest_framework.authentication import BaseAuthentication

class UserAuth(BaseAuthentication):

    msg = "认证失败"
    def authenticate(self, request):
        token = request.query_params.get("token")
        usertoken= UserToken.objects.filter(token =token).first()

        if usertoken:
            return  usertoken.user, usertoken.token
        else:
            raise  AuthenticationFailed("认证失败!")

 

4.1 应用局部认证 

class BookView(APIView):
    authentication_classes = [UserAuth]

    def get(self,request):
        """
        查看所有书籍
        :param request:
        :return:
        """
        book_list=Book.objects.all()
        serializer= BookSerializer(book_list,many=True)
        return Response(serializer.data)

    def post(self,request):
        """
        添加一条书籍
        :param request:
        :return:
        """
        serializer=BookSerializer(data=request.data,many=True)
        if serializer.is_valid():
            serializer.save()#create操作.
            return Response(serializer.data)
        else:
            return Response(serializer.errors)

  

4.2 设置全局认证模式 

REST_FRAMEWORK={

'DEFAULT_AUTHENTICATION_CLASSES': (
  'app01.utils.auth_class.UserAuth',
),

}

 

验证.

 

 

posted @ 2018-09-20 17:28  萌哥-爱学习  阅读(1796)  评论(1编辑  收藏  举报