Based on user authentication token passed
Requirements: For some of api need to access after the user logged in, and do not need to log some api can access
Solutions: a: to create two tables
b. When a user accesses the server to bring value to users token
1. Create models.py
1 from django.db import models 2 3 4 class UserInfo(models.Model): 5 user_choices_type = ( 6 (1, '普通用户'), 7 (2, 'vip用户'), 8 (3, 'svip用户'), 9 ) 10 user_type = models.IntegerField(choices=user_choices_type) 11 username = models.CharField(max_length=32, unique=True) 12 password = models.CharField(max_length=64) 13 14 15 class UserToken(models.Model): 16 user = models.OneToOneField(to='UserInfo', on_delete=models.CASCADE) 17 token = models.CharField(max_length=64)
2.urls.py
1 urlpatterns = [ 2 re_path('api/v1/auth/$', views.AuthView.as_view()), 3 re_path('api/v1/order/$', views.OrderView.as_view()), 4 ]
3. Certification Class
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 from rest_framework.authentication import BaseAuthentication 5 from rest_framework.exceptions import AuthenticationFailed 6 from api import models 7 8 9 class Authticate(BaseAuthentication): 10 11 def authenticate(self, request): 12 token = request._request.GET.get('token') 13 = models.UserToken.objects.filter token_obj (token = token) .first () 14 IF Not token_obj: 15 The raise AuthenticationFailed ( ' User authentication failed ' ) 16 return (token_obj.user, token_obj) . 17 18 is DEF authenticate_header (Self, Request ): 19 "" " 20 to return to the browser after authentication failure response header 21 is : param Request: 22 is : return: 23 is " "" 24 Pass
4.views.py
1 from django.http import JsonResponse 2 from rest_framework.views import APIView 3 from api import models 4 5 6 order_dict = { 7 1: { 8 'name': '拉皮条', 9 'age': 18, 10 'gengder': '男', 11 'content' : ' Bought inflatable ' 12 is }, 13 is 2 : { 14 ' name ' : ' hot dogs ' , 15 ' Age ' : 18 is , 16 ' gengder ' : ' M ' , . 17 ' Content ' : ' bought non Emirates ' 18 is } . 19 } 20 is 21 is 22 is DEF MD5 (User): 23 is Import hashlib 24 import time 25 ctime = str(time.time()) 26 m = hashlib.md5(user.encode('utf8')) 27 m.update(ctime.encode('utf8')) 28 return m.hexdigest() 29 30 31 class AuthView(APIView): 32 """ 33 登录相关的逻辑 34 """ 35 authentication_classes = [] 36 def post(self, request, *args, **kwargs): 37 38 ret = {'code': 1000, 'msg': None, 'token': None} 39 try: 40 user = request._request.POST.get('username') 41 pwd = request._request.POST.get('password') 42 obj = models.UserInfo.objects.filter(username=user, password=pwd).first() 43 if not obj: 44 ret['code'] = 1001 45 RET [ ' MSG ' ] = ' user name or password error ' 46 # Create a token for the user log 47 token = MD5 (User) 48 models.UserToken.objects.update_or_create (obj = User, Defaults = { ' token ' : token} ) 49 RET [ ' token ' ] = token 50 the except Exception AS E: 51 is RET [ ' code ' ] = 1002 52 is RET [ ' MSG ' ] =' Request abnormal ' 53 is 54 is return jsonResponse (RET) 55 56 is 57 is class OrderView (APIView): 58 "" " 59 orders related business 60 " "" 61 is 62 is DEF GET (Self, Request, * args, ** kwargs): 63 is Print (the request.user, request.auth) 64 RET = { ' code ' : 2000, ' MSG ' : None, ' Data ' :} None 65 the try : 66 entitled [ 'Data ' ] = order_dict 67 the except Exception AS E: 68 RET [ ' code ' ] = 2001 69 RET [ ' MSG ' ] = ' request abnormal ' 70 return jsonResponse (RET)
5.settings.py
1 REST_FRAMEWORK = { 2 'DEFAULT_AUTHENTICATION_CLASSES': ['api.utils.auth.Authticate', ], 3 # 'DEFAULT_AUTHENTICATION_CLASSES': [], # AnonymousUser None配置文件中有 4 # 'UNAUTHENTICATED_USER': lambda: '匿名用户', 5 # 'UNAUTHENTICATED_USER': None, 6 # 'UNAUTHENTICATED_TOKEN': None, 7 }
Summary : the idea is to achieve every time a user logs on, the need to bring token value, if you do not get with less than the appropriate resources, if successful login give user-created token value and returns to the user, if the second user login give user updates, but also returned to the user, of course, the user does not give the user login is successful return-related error messages.
Source process certified components analysis
Request comes first find their dispatch method without, however, left APIView parent class, method found dispatch, execute self.initialize_request method, packaging Request, preceded parser -> execution self.get_authenticators () -> [auth () for auth in self.authentication_classes] generate a list of one type authentication object ---> authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES to the default configuration file, if they have, do the initial (self, request, * args, ** kwargs ) method ----> execution self.perform_authentication (request) ------> request.user this is a static property -----> self._authenticate () ----> _ authenticate (self) - -> authenticator.authenticate (self) ----> must return a tuple.
_authenticate (self):.. All target loop certified class, authenticate authentication method of performing class 1 if the authenticate method Throws performed self._not_authenticated () 2 with a return value must be a tuple (request.user, request.auth ) 3. If it returns None, go to the next target authentication process, if all are None out of the loop , execution _not_authenticated (self) approach to configuration files if api_settings.UNAUTHENTICATED_USER is the anonymous user AnonymousUser, otherwise it is slef.user = None, self.auth = api_settings.UNAUTHENTICATED_TOKEN () is None else self.auth = None.
Built-certification class
BaseAuthentication
We write the certification class, it inherited methods must achieve authenticate method does not write directly throwing error, authenticate_header this method is an authentication failure response header information 401 to authenticate the user does not return by also must write, but generally do not do what treatment.
BasicAuthentication
This class is probably the browser after the user's password and user name sent by base64 encryption server.
SessionAuthentication
Django of the session by doing certification.
TokenAuthentication
In fact, with which I almost authentication token.
RemoteUserAuthentication
This class is authenticated request header http.