day59_9_25 middle button and login authentication

One. django middleware Introduction.

  In django, there is such life cycle:

 

 

   Middleware is in the middle and urls wsgiref module can intercept all requests, including 7 default middleware:

  MIDDLEWARE = [
  'django.middleware.security.SecurityMiddleware',
  'django.contrib.sessions.middleware.SessionMiddleware',
  'django.middleware.common.CommonMiddleware',
  'django.middleware.csrf.CsrfViewMiddleware',
  'django.contrib.auth.middleware.AuthenticationMiddleware',
  'django.contrib.messages.middleware.MessageMiddleware',
  'django.middleware.clickjacking.XFrameOptionsMiddleware',
  ]

  Where 1, 2 is safety-related, is related to the session, 4 post is submitted data related to login authentication 5 is relevant.

  There are several intermediate fixing method, wherein there are five intermediate user-defined method.

  django django Middleware is similar to that when the request needs to go through security to get django middleware backend response take the time to go through middleware to reach the web service gateway interface (urls, views, templates, models).

  The middleware can be used to do this: the global identity verification sites, frequency of access restrictions, permissions check ... as long as it relates to the global checksum you can be done in middleware.

  From top to bottom the implementation of middleware, but the response is from the bottom up.

two. Middleware Custom:

  Custom middleware need to import the module, so that the class inherits from the modules, these classes are located, is the setting in the configuration path:

from django.utils.deprecation Import MiddlewareMixin
 from django.shortcuts Import HttpResponse 

class MyMdd (MiddlewareMixin):
     DEF process_request (Self, Request):
         Print ( ' I am the first middleware inside process_request method ' ) 


    DEF process_response (Self, Request , the Response):
         Print ( ' I am the first middleware inside process_response method ' )
         return the Response 

    DEF process_view (Self, Request, view_func, view_args, view_kwargs):
         Print (view_func)
         Print(view_args)
         Print (view_kwargs)
         Print ( ' I am the first middleware inside process_view method ' ) 

    DEF process_exception (Self, Request, Exception):
         Print ( ' I am the first middleware inside process_exception ' ) 

    DEF process_template_response (Self, Request, the Response):
         Print ( ' I am the first middleware inside process_template_response ' )
         return the Response

  1.process_request () method.

  When the setting in the configuration file in the class has this method is triggered in the following cases:

  First, accept a request parameter. This request is sent to the front end. When the request will be executed from top to bottom each broker in the process_request method.

  If the direct return HttpResponse object inside, it will directly return, will not execute down. Identity verification can be carried out.

  2.process_response () method

  When you return to the front page, it will perform process_response up the value of all middleware from.

  Each method must return the response method, the method must also be accepted, and if the middleware does not return this value, an error is reported when no such interface.

  3.process_view()

  This method of rerouting a successful match, before executing the view function, and when the trigger is executed.

  Which view_func, it represents the function address.

  4.process_exception()

  When you view an error function, the function will be executed on behalf of the exception is the wrong type.

  5.process_template_response()

  This is a special type,

DEF index (Request):
     Print ( ' I am the index view function ' )
     DEF the render ():
         return HttpResponse ( ' What the hell stuff ' ) 
    obj = HttpResponse ( ' index ' ) 
    obj.render = the render
     return obj        

  If your HttpResponse object returned, there render method and they will take this middleware.

three. csrf cross-site request forgery.

  In secret information website for the user when there are some phishing sites will be mixed in there, as they look, but uses a hidden form.

  First, get some form normal page name, then do yourself a exactly the same as when the user inputs the transfer, a hidden form, name set to normal page name, manifested form name is not provided, then submit action the submission of information to the original site, this site will return to their own information.

  How to prevent this phishing website?

  The site will return to the form page form to the user secretly stuffed a random string.

  Request comes will first random strings are the same if not directly reject (403) than the right.

  This is what middleware did.

  And preventive measures, as long as the key field and then add the form:

{% csrf_token %}

  You can when rendering a template, returns a random string, name value is: csrfmiddlewaretoken, and when the form is submitted, the middleware will check this value.

 

 

   When sending ajax value, we need to get this value, the key to the way he has placed in the data submitted.

  1. Now write {% csrf_token%} page, tag lookup using the acquired key information is input.

{
    'username':'jason',
    'csrfmiddlewaretoken':$('[name=csrfmiddlewaretoken]').val()}

  2. Direct Writing '{{csrf_token}}'

{'username':'jason','csrfmiddlewaretoken':'{{ csrf_token }}'}

  3. The acquisition method may be random key written to a file js, after only need to import the file.

  First create a new js file, put the following code after the import on the line:

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');


function csrfSafeMethod(method) {
  // these HTTP methods do not require CSRF protection
  return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

$.ajaxSetup({
  beforeSend: function (xhr, settings) {
    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
      xhr.setRequestHeader("X-CSRFToken", csrftoken);
    }
  }
});
Storage js

  For more details see: Djagno official documents about the content of CSRF

four. Check the website of the global decorator

  When the time need to check csrf global website, a few do not need to check, you can import the module:

  1.fbv checksum way

from django.views.decorators.csrf import csrf_exempt,csrf_protect
@csrf_exempt
def login(request):
    return HttpResponse('login')


@csrf_protect
def lll(request):
    return HttpResponse('lll')

  In other words, when all views exempt function needs to check csrf when a certain function is not required, use exempt method.

  When all views do not need to verify csrf functions when a function requires a check on the use protect method.

  2.cbv verification method:

  For csrf_protect. There are three methods can be verified:

  This module is for a kind of decoration.

  from django.utils.decorators import method_decorator  
from django.utils.decorators import method_decorator    
from django.views.decorators.csrf import csrf_exempt,csrf_protect
# 第一种方式
# @method_decorator(csrf_protect,name='post')  # 有效的
class MyView(View):
    # 第三种方式
    # @method_decorator(csrf_protect)
    def dispatch(self, request, *args, **kwargs):
        res = super().dispatch(request, *args, **kwargs)
        return res

    def get(self,request):
        return HttpResponse('get')
     # A second embodiment 
    # @method_decorator (csrf_protect) # effective 
    DEF POST (Self, Request):
         return the HttpResponse ( ' POST ' )

  The first method is to add the methods and functions he needs to check, based on decoration.

  The second is direct to the decorative function.

  The third task is to decorate the distributor species.

  For csrf_exempt only two ways:

from django.utils.decorators Import method_decorator    
 from django.views.decorators.csrf Import csrf_exempt, csrf_protect 
@method_decorator (csrf_exempt, name = ' dispatch ' )   # the second embodiment may not check 
class the MyView (View):
     # @method_decorator (csrf_exempt) # can not check the first embodiment 
    DEF dispatch (Self, Request, * args, ** kwargs): 
        RES = Super () dispatch (Request, * args, **. kwargs)
         return RES 

    DEF GET ( Self, Request):
         return the HttpResponse ( 'get')

    def post(self,request):
        return HttpResponse('post')

  That this method can only be fitted to dispatch check, whether through class distribution or something. This is a special case, in other decorators, they can be decorated by three methods.

Fives. User login authentication component.

  In django framework, after performing the database migration command will generate a lot of tables, including a auth_user table, which is a user-related information table, the user can perform some of his memory:

  1. Create a super user.

  Using the command line to create a super user:

createsuperuser   # Create a super user can have the super-user 
privileges landing django admin backend management

  2. Query User:

  You need to import the module, which is to authenticate the user query whether the function exists:

from django.contrib Import auth 
USER_OBJ = auth.authenticate (username = username, password = password)  
 # must be used because the password field in the database is the ciphertext and you get the user input is plaintext

  This function returns a user_obj object that can be taken wherein the operation point of the user name, password and other data.

  This function does not support single user name query data, we require two together.

  3. Record the user state.

the auth.login (Request, USER_OBJ)   # user shaped state record in the session

  auth.login This method can be performed as long as the current request.user acquired by the rear end user object anywhere. Of course, these values ​​may be acquired by the operation point. If you do not run this method, it points out that an anonymous object.

  This sentence is equivalent request.session [ 'user'] = user_obj

  4. determine whether the user is logged in.

  In view of the third, by determining whether the object is to determine whether an anonymous user logon, but django to a method of determining a package:

Print (request.user.is_authenticated)   

# determine if a user is logged is your user returns False

  This passage can determine whether the login.

  5. It has the above function can be used to determine a decorator logged, but have their own encapsulation method django:

  Local configuration:

from django.contrib.auth.decorators import  login_required
@login_required(login_url='/xxx/')  # 局部配置
    def index(request):
        pass

  Where xxx is the login interface address.

  Global Configuration:

  You can configure the setting in the file:

LOGIN_URL = '/xxx/'

  This specifies that the latter may be omitted decorator.

  6. Verify that the password is correct:

  When the old password is correct when you modify the password needed to determine:

request.user.check_password(old_password)

  Returns a Boolean value.

  7. Change Password.

  Users need to be saved when the object change the password:

request.user.set_password (new_password) 
request.user.save ()   # change your password when we must save or not save the entry into force

  8. Log.

  When the Log, the equivalent of this operation request.session.flush (). The user login loading cleared.

auth.logout(request)  # request.session.flush()

  9. The user registration.

  There are three ways for registration, of which the first is not password encryption is not recommended:

 
 
from django.contrib.auth.models import User
Import user table 
#
User.objects.create (username = username, password = password)
# create a user name and then use the time do not create the
# User.objects.create_user (username = username, password = password)
# Create a regular user
User.objects.create_superuser
(username = username, password = password, Email = ' [email protected] ' )

# create a super user Email (required)

  Among them, create a super affiliate mailbox is required.

  Of course, when creating the user's need to check to see if the user exists. Such an operation requires its own table.

six. Custom user table

  Custom User table has two ways:

  1. Use one relationship is not considered.

  2. Use inherited class.

  We first need to import the class to inherit in the model layer.

from django.contrib.auth.models import AbstractUser

  Definition of the table, you can not use the original field table, can not be repeated, only innovation.

class Userinfo (AbstractUser):
     # Do not follow the original fields in the table can only repeat Innovation 
    Phone = models.BigIntegerField () 
    Avatar = models.CharField (max_length = 32)

  After creating the table, you need to configure settings in the class, as an alternative user class.

= AUTH_USER_MODEL ' app01.Userinfo '   # 'application name. Class name'

  After such a table is created in which there is no auth_user, but directly into a table that you have created. Which pack all the fields auth_user letter, the foreign key field and you add.

  Moreover, all the tables are based on the table you have created, rather than using the original table.

  This table applies to all auth method.

Seven. Middleware plug-in source code:

  as follows.

Import Settings
 Import the importlib 


DEF send_all (Content):
     for path_str in settings.NOTIFY_LIST:   # 1. one out of a string of 'notify.email.Email' 
        The module_path, path_str.rsplit class_name = ( ' . ' , maxsplit is =. 1)   # 2 from the right in accordance with a cutting point [ 'notify.email', 'In Email'] 
        Module1 = importlib.import_module (the module_path)   # from notity Import MSG, In Email, WeChat 
        CLS = getattr (Module1, class_name)   # using all reflection Thought the object are acquired from the property or method cls = a file name of a class of 
        obj = cls ()   # class instance of generating object 
        obj.send (content)  # Object transfer method

  Profiles:

NOTIFY_LIST = [
    'notify.email.Email',
    'notify.msg.Msg',
    # 'notify.wechat.WeChat',
    'notify.qq.QQ',
]

  The table structure is:

 

Guess you like

Origin www.cnblogs.com/LZXlzmmddtm/p/11588312.html