models.py
from django.db Import Models from django.contrib.auth.models Import AbstractUser class the User (AbstractUser): # inheritance AbstractUser class, so # user table fields Field introduced Mobile = models.CharField (= 64 MAX_LENGTH, UNIQUE = True) # table name set class Meta -: named db_table, = ' api_user ' the verbose_name = ' user table ' verbose_name_plural = the verbose_name DEF __str__ (Self): return self.username
The migration model table above, if the migration is not successful, the required profile venv ===> site-packages ===> django ===> contrib ===> admin ===> migration file in addition to file __init__ , are deleted.
Migrating to MySQL in the following figure: The user is a super user, the user created using the migration command
user表
Group table, authority table, user table and the group table even table, group table even with the permission table table
Operating Table
test.py test file
import os import sys, django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'day74.settings') django.setup() from django.contrib.auth.models import Group group = Group.objects.all().first() print(group.name) # 从分组到用户查 user_set print(group.user_set.first().username) # 从分组到权限表, permissions from api import models user = models.User.objects.first() print(user.username) # Check packet from a user list table Print (user.groups.first (). Name) Print ()
Certified Components
1) APIView of dispath (Self, Request, * args, ** kwargs) within 2) dispath method self.initial (Request, * args, ** kwargs) into the largest certification # authentication component: check users - tourists, legal users, unauthorized users # guests: representatives of the check is passed directly to the next check (check the permissions) # legitimate users: check by representatives, will request.user, and then enter the user store next check (school authority test) # unauthorized users: On behalf of the check fails, an exception is thrown, return 403 permissions abnormal results self.perform_authentication (Request) # privilege components: check user rights - must log all user, login to read and write read-only visitors, custom user roles # authentication: You can enter the next check (frequency certification) # authentication failure: an exception is thrown, return 403 permissions abnormal results self.check_permissions (Request) # frequency components: limit the number of times the frequency of view of the interface is accessed - restrictions condition (IP, id, a unique key), the frequency of the cycle time (s, m, h), times (3 / s) frequency # does not reach the time limit: normal access interface # reached the limit time: time limit Can not be accessed, time to reach the limit, you can re-access self.check_throttles (Request) . 3 ) Authentication Unit Method Request class of user attribute get method => self._authenticate () completes the authentication certification Details: # do authentication DEF _authenticate (Self): # traversed to get one authenticator, authentication # authentication class object pile is configured to generate authentication self.authenticators class consisting List for Authenticator in self.authenticators: the try : # Authorizer (object) calls the authentication method authenticate (certified class object self, request the requested object) # return value: tuple information and user authentication landing composition # this method is try wrapped, on behalf of the method will throw an exception, throw an exception on behalf of authentication failure user_auth_tuple = authenticator.authenticate (Self) the except exceptions.APIException: () self._not_authenticated The raise # handle the return value of the IF user_auth_tuple IS not None: self._authenticator = Authenticator # How to return a value, it will login and login authentication are saved to request.user, request.auth self.user, self.auth = user_auth_tuple return # If the return value is null user_auth_tuple, on behalf of authenticated, but not logged in user login and authentication information, on behalf of tourists self._not_authenticated () 4 ) rights component self.check_permissions (request) certification Rules : DEFcheck_permissions (Self, Request): # traverse permissions for a list of objects to get a permission object (an authority), a certification authority for permission in self.get_permissions (): # permission class must have a permission has_permission method, used for certification authority # parameters: rights object self, request object request, view class object # return value: returns have permission True, no authority returns False IF not permission.has_permission (request, Self): self.permission_denied ( request, Message = getattr (permission, ' Message ' , None) )
Custom authentication component
1 ) Creating inheritance BaseAuthentication authentication class 2 ) implemented authenticate method 3 ) implementation thereof is determined tourists, illegal users based on the authentication rules, authorized users 4 ) globally or locally configure authentication rules i. No certification information is returned None (tourists) II. There authentication information fails throwing an exception (illegal users) iii. has successfully returned to the user authentication information and authentication information tuple (legitimate users)
Examples of custom authentication component
from rest_framework.authentication Import BaseAuthentication from rest_framework.exceptions Import AuthenticationFailed from . Import Models class MyAuthentication (BaseAuthentication): "" " with the front desk to get authentication information request header auth (authentication field to get the reception in the agreement) no auth tourists, return None there auth checksum failure is an illegal user, an exception is thrown success is a legitimate user, return (user authentication information) "" " DEF the authenticate (Self, request): # foreground carrying authentication information in the request header, # and the default specification Authorization field carries authentication information # background field of the request META fixed object acquired HTTP_AUTHORIZATION = request.META.get auth ( ' HTTP_AUTHORIZATION ' , None) # processing Tourists IF auth IS None: return None # set about the small field certification rule (two-stage): "auth authentication string" auth_list = auth.split () # verify lawful or unlawful user IF not (len (auth_list) == 2 and auth_list [0] .lower () == ' auth ' ): the raise AuthenticationFailed ( ' authentication information is incorrect, illegal user ' ) # legitimate users We need to resolve the auth_list [1] out of #Note: a case is assumed, information abc.123.xyz, admin users can be parsed; actual development, the logic must check logic is a normal user IF auth_list [. 1] =! ' Abc.123.xyz ' : # check fails The raise AuthenticationFailed ( ' user verification fails, the illegal user ' ) user = models.User.objects.filter (username = ' ADMIN ' ) .first () IF Not user: The raise AuthenticationFailed ( ' user data error, illegal user ' ) return (user, None)
= REST_FRAMEWORK { # Global configuration module abnormal ' EXCEPTION_HANDLER ' : ' utils.exception.exception_handler ' , # authentication configuration class ' DEFAULT_AUTHENTICATION_CLASSES ' : [ # ' rest_framework.authentication.SessionAuthentication ', # ' rest_framework.authentication.BasicAuthentication ', ' utils. authentications.MyAuthentication ' , ], # permission classes configure ' DEFAULT_PERMISSION_CLASSES ' : [ ' rest_framework.permissions.AllowAny', 'utils.permissions.MyPermission' ], }
Add properties introduced in the view class
permission_classes = [MyAuthentication]
Custom permission assembly
1 ) Create BasePermission inherited permission class 2 ) has_permission implemented method 3 ) implemented to determine whether the body according to the permission rights rules 4 ) globally or locally configure authentication rules i. The user setting condition is satisfied, representing authority, returns True II. No meet the conditions set by the user, representing authority, returns False
Custom permissions component instance
from rest_framework.permissions import IsAuthenticated from utils.permissions import MyPermission class TestAuthenticeatedAPIView(APIView): permission_classes = [IsAuthenticated, MyPermission] def get(self, request, *args, **kwargs): return APIResponse(0, 'test 登陆才能访问!') def post(self, request, *args, **kwargs): return APIResponse(0, "自定义 ok!")
from rest_framework.permissions import BasePermission from django.contrib.auth.models import Group class MyPermission(BasePermission): def has_permission(self, request, view): # 只读接口判断 r1 = request.method in ('GET', 'HEAD', 'OPTIONS') # group为有权限的分组 group = Group.objects.filter(name='管理员').first() # groups为当前用户所属的所有分组 groups = request.user.groups.all() r2 = group and groups r3 = group in groups # 读接口大家都有权限,写接口必须为指定分组下的登陆用户 return r1 or (r2 and r3)
setting文件配置上面setting文件配置