django middleware
The complete life cycle:
django Middleware is similar to a django security
When a request needs to go through middleware to reach django backend (urls, views, templates, models )
In response take the time to go through middleware to reach the web service gateway interface
django default seven 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',
]
django middleware methods have five users can customize
django middleware can be used to do what (**********************************************************)
1. Website global identity verification , access frequency restrictions , permissions check ... as long as it relates to the global checksum you can be done in middleware
2.django middleware is all web frameworks do best
How to customize our own middleware, five research methods What are the characteristics of the above
1. If you want your writing middleware to take effect it must first inherit MiddlewareMixin
2. When registering a custom middleware must ensure that the path not wrong
We need to master methods
1.process_request () method
law
1. When the request goes through the inside of each intermediate process_request method ( from top to bottom )
2. If the direct method which returns a HttpResponse objects that will no longer execute directly back down
We can do access restrictions based on the frequency characteristics , identity verification , permission to check
2.process_response () method
law
1. must response parameter to return because of this parameter is to refer back to the front end of the data
2. The response will in turn take the time to go through each broker inside process_response method ( bottom-up )
You need to understand the way
3.process_view()
1. triggered before routing to match the successful implementation of the view function
4.process_exception()
1. will be performed automatically when you view function error
5.process_template_response()
1. When you return to the HttpResponse object must contain render attributes will trigger
def index(request):
print ( ' I am the index view function ')
def render():
return HttpResponse ( ' What the hell stuff ')
obj = HttpResponse('index')
obj.render = render # to obj add an attribute, attribute named render , attribute value render
return obj
Summary : as long as you have the time parameter in writing middleware repsonse you feels that she returned this reponse is to give the front end of the message
csrf CSRF
Phishing sites
By making eight children with a site exactly the same page , trick users to enter information transfer transactions
Thus tamper with transfer transaction request is indeed sent to the Bank of China , account money is indeed
Less the only place that is not the same payee accounts are not available
Internal principle
In other accounts allow users to input the input above tricks
Give this input is not set the name property , hidden inside a pre-written name and value attributes input box
The value of the account value is the beneficiary of phishing sites
Ideas to prevent phishing sites
The site will be returned to the user's form form page secretly stuffed a random string
Request comes will first than random strings are the same if not directly reject (403)
The random string has the following characteristics
1. same browser each visit is different
2. different browsers will not be repeated
1.form form to send post request : you need to do is just write a word (no need to comment out the line middleware)
{% csrf_token %}
2.ajax sending post request avoiding csrf three ways check
1. Now write the page {% csrf_token%}, using the tag lookup to obtain the input key information
{'username':'jason','csrfmiddlewaretoken':$('[name=csrfmiddlewaretoken]').val()}
$('[name=csrfmiddlewaretoken]').val()
2. Direct Writing '{{csrf_token}}'
{'username':'jason','csrfmiddlewaretoken':'{{ csrf_token }}'}
{{ csrf_token }}
3. You can get the key method for random writes a js file , then just import the file to
Create a js import file can be stored after the following code (set to static list of files, STATICFILES_DIRS to the settings provided, then after introduction)
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); } } });
1. When the global site you need to check csrf time there are a few do not need to check how this process
2. When the global website you do not check csrf when there are a few need to verify what should we do
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt,csrf_protect
Direct decorator when FBV decoration: @csrf_exempt and @crsf_protect
# The two decorators in to the CBV is quite different when decorating
If csrf_protect then there are three ways
# The first way
# @Method_decorator (csrf_protect, name = ' post') # effective
class MyView(View):
# The third way
# @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')
# The second way
# @Method_decorator (csrf_protect) # Effective
def post(self,request):
return HttpResponse('post')
If csrf_exempt only two ( only to dispatch equipment ) exception
@method_decorator (csrf_exempt, name = 'dispatch ') # the second embodiment may not check
class MyView(View):
# @Method_decorator (csrf_exempt) # the first embodiment may not check
def dispatch(self, request, *args, **kwargs):
res = super().dispatch(request, *args, **kwargs)
return res
def get(self,request):
return HttpResponse('get')
def post(self,request):
return HttpResponse('post')
Summary decorator only csrf_exempt is a special case , other decorators in to CBV when decorating can have three ways
Homework :
The landing yesterday written certification decorator load CBV on
auth function module
Query User
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
Record user status
the auth.login (Request, USER_OBJ) # user status record to the session in
As long as this line of code is executed, at an arbitrary position by the rear end request.user acquiring the current user object.
Determine whether the user is logged
print (request.user.is_authenticated) # determine if a user is logged anonymous user returns False
After logging the user to obtain the user object
print (request.user) # If no auth.login then got an anonymous user
Check whether the user is logged (decorator)
from django.contrib.auth.decorators import login_required
@login_required (login_url = '/ xxx / ') # local configuration , login_url may control the page jump is not logged.
def index(request):
pass
# Global configuration settings file , control above decorator jump page
LOGIN_URL = '/xxx/'
Verify the password is correct
request.user.check_password(old_password)
change Password
request.user.set_password(new_password)
request.user.save () # change your password when we must save save or can not take effect
sign out
auth.logout(request) # request.session.flush()
registered user
# User.objects.create (username = username, password = password) # create a user name and then use the time do not create a since records created password is not encrypted
# User.objects.create_user (username = username, password = password) # Create a regular user
User.objects.create_superuser (username = username, password = password, email = '123 @ qq.com') # Create a super user Email (required)
Custom auth_user table
from django.contrib.auth.models import AbstractUser
# Create your models here.
# The first uses one relationship is not considered
# Inherit second way to use class
class Userinfo(AbstractUser):
# Do not repeat the only innovation in the field with the original table
phone = models.BigIntegerField()
avatar = models.CharField(max_length=32)
# Be sure to tell the configuration file django
# Tell django orm no longer use the auth default table but use your custom table
AUTH_USER_MODEL = 'app01.Userinfo' # ' application name . Class name '
1. perform a database migration command (need to set up a new database)
All auth module functions are all based on the table you created
Rather than using auth_user
settings function plug-source implementation of the principle. (The last in a knowledge day59)