zoukankan      html  css  js  c++  java
  • 认证组件

    简介

    只有认证通过的用户才能访问指定的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')
    

    源代码流程

    见认证组件源代码分析

  • 相关阅读:
    IntelliJ IDEA Community Edition 14.1.4下使用 Apache-Subversion搭建代码管理环境
    Eclipse+SVN搭建开发环境
    查看分区表中分区详细信息
    asp.net mvc 后台怎么接受前端返回的array list dictionary
    jquery 操作select
    asp.net mvc4 System.Web.Optimization找不到引用
    asp.net mvc4 设置build项目时,编译view页面
    c# ConfigurationSection
    Array基本操作
    For,Function,Lazy
  • 原文地址:https://www.cnblogs.com/kp1995/p/10612639.html
Copyright © 2011-2022 走看看