Luffy Xuecheng project - Login Authentication Module

 

############### registration interface ################

################## registered logical analysis ############################ 
# front: 
# 1, the front, pass over user name and password, the front end can pass a lot of things, such as head occupation, etc., 
# backend, 
# 1, url, 
# 2, View, the Register class, 
# 3, Model, 
# 4, serializers 

################## the Register class ############################ 
# 1, to obtain a user name and password, 
# 2, take serializer be verified, 
# 3, after the registration is successful, save the data to the database and return the registration is successful, the need to return additional information such as user name, need to see the front end of 

#### ############## serializer logic ############################ 
# 1, need to rewrite the create method is called when the save method, because of the need to encrypt pass over the pwd, it needs to be rewritten, 

################## table model analysis : ############################ 
# registered a username, password, token, token creation time, the 
# Note: 
# 1, password encryption during transmission needs, how to encrypt? How md5 encryption? 
# 2, how to achieve seven days free login?

 

class Register(APIView):
    def post(self,request):
        ser_obj = UserInfoSerializers(data=request.data)
        if ser_obj.is_valid():
            ser_obj.save()
            return Response('注册成功')
        else: return Response(ser_obj.errors)

 

 

############### landing Interface ################

################## landing logical analysis ############################ 
# distal: 
# 1, a front end, pass over the user name and password 
# rear end, 
# 1, URL, 
# 2, View, Login class, 
#. 3, Model, 
#. 4, serializers 

############ ###### login class ############################ 
# 1 obtains the user name and password, 
# 2, there is no determination this user object, 
# 3, if there is generated token value, 
# 4, return landing success or failure information 
# Note: 
# write code must try, it is a coding practice, to prevent the collapse of your code 

###### ############ BaseException class ############################ 
# 1, inheritance Object, 
# 2 , the way into the decorator attribute, 
# 3, initialization of the definition of the properties

 

class the Login (APIView): 

    DEF POST (Self, Request): 
        RET = BaseException () 
        username = request.data.get ( 'username', '' )  IF Not username:  ret.code = 1001 ret.error = 'username can not be empty ' pwd = request.data.get (' pwd ',' ' ) IF not pwd: ret.code = 1002 ret.error =' password is not blank 'the try : USER_OBJ = UserInfo.objects.filter (username = username, pwd = pwd) .first () IF not USER_OBJ: ret.code = 1003 ret.error = 'user or password is incorrect' user_obj.token = uuid.uuid4 () user_obj.save () ret.data = 'successful landing 'the except Exception AS E: = 1004 ret.code ret.error = 'Login Failed' return Response (ret.dict)

 

############### Certification ################

################## authentication logic analysis ############################ 
# front-end 
# 1, access to other pages need to carry a token, 
# 2, the front end can be worn inside the header, 
# backend: 
# 1, get to the front end pass over the token, this value may be placed header inside pass over, it can be inside pass over into the url, 
# 2, to determine whether there is the token 
# 3, to determine whether the token expired, expired are not logged in, do a check, which is seven days free login, 
# 4, returns a tuple,

 

class TokenAuth (BaseAuthentication): 
    DEF the authenticate (Self, Request): 
        # Get pass over the front end token, the header is placed inside 
        # Print (request.META) 
        token = request.META.get ( 'HTTP_AUTHENTICATE', '' ) 
        Print (token)  iF not token:  The raise AuthenticationFailed ({ "code": 1001, "error": "does not carry a token" }) # determines whether there is a token = UserInfo.objects.filter USER_OBJ (token = token) .first () Print (USER_OBJ) iF not USER_OBJ: The raise AuthenticationFailed ({ "code": 1002, "error": "illegal token" }) = # determines whether expired old_time USER_OBJ.create_token_time now_time = now() print((old_time-now_time).days) if (now_time-old_time).days > 7: raise AuthenticationFailed({"code":1003,"error":"token过期"}) return (user_obj,token)

 

############### demand ################

Landing and certification, 
each interface must be landed before they can access, 
use the token to login authentication, and access interfaces, 

certification has a new understanding, authority, frequency of usage of these three components, as 
required feel for,

 

############### Table Structure ################

class UserInfo(models.Model):
    user = models.CharField(max_length=32)
    pwd = models.CharField(max_length=64)

class UserToken(models.Model):
    user = models.OneToOneField(to="UserInfo")
    token = models.CharField(max_length=64)

 

############### login authentication ################

from rest_framework.views import APIView
from rest_framework.response import Response
from django.shortcuts import HttpResponse
from api import models
import uuid


class AuthView(APIView):

    def post(self,request,*args,**kwargs):
        """
        用户登录认证
        :param request:
        :param args:
        :param kwargs:
        :return:
        """

        ret = {'code':1000}
        user = request.data.get('user')
        pwd = request.data.get('pwd')

        user = models.UserInfo.objects.filter(user=user,pwd=pwd).first()
        if not user:
            ret['code'] = 1001
            ret['error'] = '用户名或密码错误'
        else:
            uid = str(uuid.uuid4())
            models.UserToken.objects.update_or_create(user=user,defaults={'token':uid})
            ret['token'] = uid
        return Response(ret)

 

############### access interface certification class ################

from rest_framework.authentication Import BaseAuthentication
 from rest_framework.exceptions Import AuthenticationFailed
 from API Import Models 

class LuffyAuth (BaseAuthentication): 

    DEF the authenticate (Self, Request):
         "" " 
        authentication token need to obtain transfer of the front end, and checking whether there is, 
        : param Request: 
        : return: 
        "" " 
        token = request.query_params.get ( ' token ' ) 
        obj = models.UserToken.objects.filter (token = token) .first ()
         IF  Notobj:
             The raise AuthenticationFailed ({ ' code ' : 1001, ' error ' : ' authentication failure ' })
         return (obj.user.user, obj)   # authentication is successful returns a tuple,

 

Authentication view ############### ################

class MicroView(APIView):
    # 认证
    authentication_classes = [LuffyAuth,]

    def get(self,request,*args,**kwargs):
        ret = {'code':1000,'title':'微职位'}
        return Response(ret)

 

############### Table Structure ################

 

Guess you like

Origin www.cnblogs.com/andy0816/p/12302022.html
Recommended