Django Framework Deeply Understanding _03(DRF Authentication Component, Permission Component)

Keywords: PHP Database Django

I. Authentication Components

Usage method:

Write a certification class and create a new file: my_examine.py

# Import base classes that need inheritance BaseAuthentication
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from app01 import models

# Create authentication classes, inherit BaseAuthentication
class MyAuth(BaseAuthentication):
    # Write one on a regular basis authenticate Method is used to define specific authentication content
    def authenticate(self, request):
        # Write Authentication Logic Code
        # Let's say hypothesis token The data exists in the back-end database, and the requests sent by the front-end need to be authenticated. token
        token = request.GET.get('token')
        token_obj = models.Token.objects.filter(token=token).first()
        if token_obj:
            # Valuable Representation token Verification pass
            # have access to token_obj.user Get the currently logged in user object
            
            # Here you need to return two data
            return token_obj.user, token_obj
        else:
            raise AuthenticationFailed('Unauthorized')

Local Use: Add Authentication to View Class:

from app01.my_examine import MyAuth
# Create your views here.

class Books(APIView):
    # to Books View class addition token Authentication
    authentication_classes = [MyAuth, ]
    def get(self, request):
        response = {'code': 100, 'msg': 'query was successful'}
        books = models.Book.objects.all()
        books_ser = BookSer(instance=books, many=True)
        response['data'] = books_ser.data
        return Response(response)

Global Authentication Usage Settings:

Configuration in settings.py

REST_FRAMEWORK={
                "DEFAULT_AUTHENTICATION_CLASSES":["app01.my_examine.MyAuth",]
            }

 

Global authentication has been set, and all classes in the view will be authenticated with set values, which is obviously not practical, because some views can not set authentication, such as registration, login.

So it is necessary to disable authentication locally.

Add the following code to the locally authenticated view class location to complete the locally disabled
authentication_classes = []

 

Summary: (by analyzing the source code)

- If REST_FRAMEWORK is configured in the project settings.py, the default is to fetch it from the project settings first.
            - If not, go to the default drf configuration file
            - If a user configures a view class, go to the user configuration fetch first.
            
            Summary:
                Select the default configuration in the view class

token briefly describes:

The token implementation process: after the user logs in successfully, the server calculates the user-related and unique string (token) through its own encryption algorithm and sends it to the front end together with the responding data. The front end saves the token data. The next time the user accesses the sending request, the token data will be sent to the back-end server, and the next time the user accesses the sending request, the token data will be sent to the back-end server. The end server first checks the token (which can be in the middleware or in the view). The process of checking is roughly to calculate the token string of the user again through the encryption algorithm of the user's relevant data, and to compare the token calculated now with the token saved in the front end user's sending. With this token, if it is consistent, the login is successful on behalf of the user authentication, of course, the token can set the valid time. To some extent, it relieves the pressure of the server.

Using token to write login interface:

models.py

# models.py

class User(models.Model):
    name = models.CharField(max_length=32)
    password = models.CharField(max_length=64)
    choices = (('1', 'Super_Admin'), ('2', 'General_Admin'), ('3', 'General_User') )
    user_type = models.CharField(max_length=6, choices=choices, default='3')

#with User Tables do one-to-one associations
class Token(models.Model):
    token = models.CharField(max_length=64)
    user = models.OneToOneField(to='User')

 

 

 

views.py

# views.py

from rest_framework.response import Response
from app01.my_examine import MyAuth
# Create your views here.

from uuid import uuid4
from django.core.exceptions import ObjectDoesNotExist
class Login(APIView):
    def post(self, request):
        response = {'code': 100, 'msg': 'Successful login'}
        name = request.data.get('name')
        password = request.data.get('password')
        try:
            # Use get Method, get Method can only take one piece of data, if it is multiple or not, it will throw an exception.
            user = models.User.objects.filter(name=name, password=password).get()
            # adopt try Method catches exceptions. If you go here, there are no exceptions. get Method fetches the user object and the user logs in successfully.
            # Login Success Requirements token Data preservation of tables(Let's assume that. token Is saved in the server-side database)
            # Generating a sanitary garment id,Use uuid Modular
            token = uuid4()
            # token If it exists in the user database, it is updated, and if it does not, it is created.
            # Use update_or_create Method
            models.Token.objects.update_or_create(user=user, defaults={'token': token})
            # take token Put it in the returned dictionary
            response['token'] = token
        # Catch a special exception. user Objects that do not exist go here
        except ObjectDoesNotExist as e:
            response['code'] = 101
            response['msg'] = 'ERROR Incorrect username or password'
        # Capture other exceptions
        except Exception as e:
            response['code'] = 102
            response['msg'] = 'unknown error'
        # Return front-end data
        return Response(response)

 

Add routing:

url(r'^login/', views.Login.as_view()),

 

Privilege Components

The use of permission components is basically the same as that of authentication components:

Usage method:

Write a permission class, still in my_examine.py:

from rest_framework.permissions import BasePermission
# Create authentication classes, BasePermission
class MyPermission(BasePermission):
    msg = 'Insufficient permissions to view'
    # Write one on a regular basis has_permission Method is used to define specific permission content
    def has_permission(self, request, view):
        # #Because permissions are executed after authentication, all can be retrieved to reuqest.user.
        if request.user.user_type == '1':
            return True
        else:
            return False

 

Local use:

-Write in view class
permission_classes=[MyPermision,]

 

Global use:

stay settings.py Configuration in
REST_FRAMEWORK={
    "DEFAULT_PERMISSION_CLASSES":["app01.my_examine.MyPermision",]
}

 

Locally disabled:

-Write in view class
permission_classes = []

 

Here you can set up to add a code to return to display Chinese prompts:

# stay MyPermision Add below the class
msg = 'Insufficient permissions to view'

Posted by wit77 on Wed, 03 Jul 2019 11:47:59 -0700