• Django Rest Framework 认证组件


    '''用户认证章节'''
    
    # 用户认证章节:写一个数据接口
    from django.http import JsonResponse
    from .utils import get_token
    from rest_framework.exceptions import APIException
    
    
    class UserView(APIView):
        def post(self, request):
            # 定义返回消息体
            response = dict()
            # 定义需要的用户信息
            fields = {"username", "password"}
            # 定义一个用户信息字典
            user_info = dict()
    
            if fields.issubset(set(request.data.keys())):
                # username = request.data.get("username")
                # password = request.data.get("password")
                for key in fields:
                    user_info[key] = request.data[key]
    
            user_instance = models.UserInfo.objects.filter(**user_info).first()
    
            if user_instance is not None:
                access_token = get_token.genertate_token()
                models.UserToken.objects.update_or_create(user=user_instance, defaults={
                    'token': access_token
                })
    
                response["status_code"] = 200
                response["status_message"] = "登录成功"
                response["access_token"] = access_token
                response["user_role"] = user_instance.get_usertype_id_display()
            else:
                response["status_code"] = 201
                response["status_message"] = "登录失败,用户名或密码错误"
    
            return JsonResponse(response)
    
    
    # 定义一个认证类
    class UserAuth():
        def authenticate_header(self):
            pass
        def authenticate(self, request):
            user_token = request.query_params.get("token")
            try:
                #获取token
                token = models.UserToken.objects.get(token=user_token)
                return token.user.username,token.token
            except Exception:
                raise APIException("没有认证")
    
    
    from rest_framework.viewsets import ModelViewSet
    class BookView(ModelViewSet):
        # 在需要认证的数据接口里面指定认证类
        authentication_classes = [UserAuth]
        queryset = models.Book.objects.all()
        serializer_class = BookSerizlizer
    views.py
    import uuid
    #创建随机字符串用作token
    def genertate_token():
        res = str(uuid.uuid4()).replace('-','')
        return res
        re_path(r'user/$',views.UserView.as_view()),

    全局组件:

    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': [
            'books.authentication_classes.UserAuth'
        ], 
    }
    settings.py

    在项目应用目录下新建一个authentication_classes.py文件.把views.py里面的定义认证类转移过来。

    from rest_framework.exceptions import APIException
    #导入BaseAuthentication类
    from rest_framework.authentication import BaseAuthentication
    from . import models
    # 定义一个认证类
    class UserAuth(BaseAuthentication):
        def authenticate_header(self):
            pass
        def authenticate(self, request):
            user_token = request.query_params.get("token")
            try:
                #获取token
                token = models.UserToken.objects.get(token=user_token)
                return token.user,token.token
            except Exception:
                raise APIException("没有认证")
    View Code
  • 相关阅读:
    rails s 命令不起作用
    ubuntu下virtualbox共享usb
    ubuntu15.04 无法识别exfat格式
    .net core 2.2 修改IdentityUser主键标识类型
    Mac os 安装node.js及环境变量的配置过程
    常见互联网网络名词整理
    assert的用法
    Mac系统中 改变 pip总是默认安装在Mac上自带的python上为python3
    测试工程师的发展之路
    MySQL的mysql-8.0.17-winx64版本安装过程中遇到的问题
  • 原文地址:https://www.cnblogs.com/cou1d/p/12342689.html
Copyright © 2020-2023  润新知