day94-Authentication component & permission component & access rating limit

day94-Authentication component & permission component & access rating limit

1. Certified components

1.1 Define authentication and create a new auth.py file

1.1.1 Inherit BaseAuthentication

1.1.2 The hook function name is determined

1.1.3 Return value returns two parameters, request.user and request.auth, namely user_obj and token

1.1.4 There are many ways to obtain tokens, see sticker

from rest_framework import authentication
from django.core.cache import cache
from rest_framework.request import Request
from rest_framework.exceptions import AuthenticationFailed
from app_auth import models

class Authentication(authentication.BaseAuthentication):
    def authenticate(self, request: Request):
        token = request.META.get('HTTP_AUTHORIZATION') # redis get token
        user_pk = cache.get(token) # get user_id with token
        if user_pk:
            user_obj = models.User.objects.filter(pk=user_pk).first()
            cache.set(token, user_pk, 60 * 20) # redis resets the maximum expiration time
            return user_obj, token
        raise AuthenticationFailed('Illegal operation') # no tok

1.2 Using authentication components in the view

1.2.1 Import the authentication class written by yourself, use the method as follows, you can receive multiple

class TestView(APIView):
    # Direct use of authentication components
    authentication_classes = [auth.Authentication,]

    def get(self, request):
        return Response('Test certification component')

2. Permission component

2.1 Define permissions and create a new permissions.py file

2.1.1 Inherited BasePermission

2.1.2 Define message, define the content as error message

2.1.3 How many types of permissions are defined, see the texture

from rest_framework import permissions
from rest_framework.request import Request


class UserPermission(permissions.BasePermission):
    message ='Insufficient permissions'

    def has_permission(self, request: Request, view):
        # request.user.has_perm()
        # Supertubes are all True
        if'app01.view_book' in [item for item in request.user.get_all_permissions()]:
            return True
        return False

2.2 Use permission components in the view

2.2.1 Import the permission class written by yourself, use the method as follows, you can receive multiple

class TestPermission(APIView):
    # Authentication
    authentication_classes = [auth.Authentication,]
    # Permission
    permission_classes = [permissions.UserPermission,]

    def get(self, request):
        return Response('You can watch vip movies')

3. Access frequency restriction component

3.1 Define the access frequency class and create a new throttle.py file

3.1.1 Inherit SimpleRateThrottle

3.1.2 The content of scope is defined in settings

3.1.3 The rest of the content remains unchanged

from rest_framework.throttling import SimpleRateThrottle


class MyThrottle(SimpleRateThrottle):
    scope ='MM'

    def get_cache_key(self, request, view):
        # Get the ip address
        return self.get_ident(request)

3.2 Configuration in settings

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [],
    # Add as follows, which means that the same ip can be accessed 3 times a minute
    "DEFAULT_THROTTLE_RATES": {"MM": "3/m",}
}

3.3 How to define access frequency

3.4 Use frequency limit components in the view

3.4.1 Import the frequency limit class written by yourself, use the method as follows, you can receive multiple

class TestPermission(APIView):
    # Authentication
    authentication_classes = [auth.MyAuth,]
    # Permission
    permission_classes = [permissions.MyPermission,]
    # Restrict access
    throttle_classes = [throttle.MyThrottle]

    def get(self, request):
        return Response('You can watch vip movies')

3.5 Reference example code: limit frequency logic

import time

VISIT_RECORD = {}


class MyThrottle(object):
    """
    Allow 5 visits per minute
    """

    def __init__(self):
        self.history = []

    def allow_request(self, request, view):
        # Get the user's IP address
        ip = request.META.get("REMOTE_ADDR", "")
        if ip not in VISIT_RECORD:
            VISIT_RECORD[ip] = [time.time(),]
        else:
            history = VISIT_RECORD[ip]
            self.history = history
            history.insert(0, time.time())
            # Ensure that the list time is within the allowable range
            while self.history[0]-self.history[-1]> 60:
                self.history.pop()
            # Determine the length of the list
            if not len(self.history) <= 5:
                return False
        return True

    # waiting time
    # [Recent time, oldest time]
    def wait(self):
        return 60-(self.history[0]-self.history[-1])
Reference: https://cloud.tencent.com/developer/article/1595662 day94-authentication component & permission component & access rating limit-cloud + community-Tencent Cloud