The middleware and csrf day61 django module auth

First, based on the configuration file programming ideas

reflection

By string manipulation functions and classes

1. importlib module

Importlib module corresponding module can be removed through a string.

import importlib

res = 'lib.bbb'
# 利用字符串的形式导入模块
md = importlib.import_module(res)  
# from lib import bbb md相当于bbb
print(md)  # 该模块字符串最小单位只能到文件名

2. Profiles

When we import a module, we actually import a folder of this module file __init__.pyfile.

The file can be imported configuration information file.

We will advance import other specific path to the module in a configuration file written in the form of a string, save to configuration information.

Then __init__.pythrough the module configuration file importlib imported file parsing the configuration information string into a real path import module.

So that we can enter a string in the configuration file to import the module it! And if we have no need to use some of the modules and functions, we will direct path string in the configuration file comment out the line.

Second, cross-site request forgery (CSRF)

1.csrf Introduction and Origin

Cross-Site Request Forgery: cross-site request forgery

Some phishing sites will be written with regular site like interface, and induce users to submit data. When phishing sites after receiving the user had wanted to send data to the regular site, phishing sites set these information with some modifications to its key information into the data they want, and then sent to the web site this set of modifications to the regular site for processing.

Such phishing sites to steal user information to achieve the purpose and profit from. This will enable the user to legitimate Web sites suffer.

In order to prevent such a situation, the formal acceptance of the site to do some data processing. The provisions of this website will only deal with post their own requests submitted on this page.

This ensures that the failure of phishing sites from Cross-Site Request sent me.

It is used for the intermediate csrf such operations. With this middleware, the back end when sending HTML page to the front, will be added in the form in a form input box with the name attribute, and value is the user's real account login, and then hide the label.

So the user at the time of submission of the data, you can check whether the back end you have this hidden tag, if there is, it shows that you are a real user. If not, it shows a fake request sent to other sites.

This can be done to ensure that the purpose of the rights and interests of users.

How 2.Django the use of middleware csrf

When csrf intermediate in the configuration file has been written, unless the middleware comments, it will automatically send an HTML help files rear end toward the front end, added csrf_token.

In this case the front end to the rear end of the need to send data, it is necessary to check carry csrf_token parameters, the tip of the rear end of the data by checking csrf.

2.1 ordinary form form submission data

How to carry the front csrf_token:

{# 你只需要在表单中写一个{% csrf_token %} #}
<form action="" method="post">
    {% csrf_token %}   
    {# csrf_token必须写在form表单里面 #}
    <p>username:<input type="text" name="username"></p>
    <p>target_account:<input type="text" name="target_user"></p>
    <p>money:<input type="text" name="money"></p>
    <input type="submit">
</form>

2.2 ajax submit data

Method 1: is more complicated

Writing the first page of any positions {% csrf_token%};

Then look through the label ajax request when sending random string acquisition, data added to the objects can be custom.

<script>
    $('#d1').click(function () {
        $.ajax({
            url:'',
            type:'post',
            // 第一种
            data:{
                'username':'jason',
                'csrfmiddlewaretoken':$('input[name="csrfmiddlewaretoken"]').val()
            },
            success:function (data) {
                alert(data)
            }
        })
    })
</script>

Option 2: simple

<script>
    $('#d1').click(function () {
        $.ajax({
            url:'',
            type:'post',
            // 第二种
            data:{
                'username':'jason',
                'csrfmiddlewaretoken':'{{ csrf_token }}'  {# 要加一下引号 #}
            },  {# 要加一下引号 #}
            success:function (data) {
                alert(data)
            }
        })
    })
</script>

Mode 3: official website provides file (the most common kind of way)

New files are copied directly js code can be introduced;

You do not need to do any of the relevant code writing csrf

You do not need to do any of the relevant code writing csrf

<script src="/static/setup.js"></script>
<script>
    $('#d1').click(function () {
        $.ajax({
            url:'',
            type:'post',
            // 第三种  利用脚本文件 啥也不用写
            data:{'username':'jason'},
            success:function (data) {
                alert(data)
            }
        })
    })
</script>

3.csrf related decorator

3.1 csrf_exempt

If you need to set up a global middleware check csrf, then the decorative function lets not be verified.

# @csrf_exempt  # 不校验 csrf
def index(request):
    return HttpResponse('index')  # 不需要也可以交互

3.2 csrf_protect

If csrf middleware commented out, set the global parity csrf not, then the function may

@csrf_protect  # 校验
def login(request):
    return HttpResponse('login')

3.3 How to use the above two functions in the function of CBV

  1. csrf_exempt this decorator can only be fitted to dispatch to take effect;
  2. csrf_protect any way they can, and general decor decorator CBV consistent.
# @method_decorator(csrf_exempt,name='post')  # csrf_exempt不支持该方法
@method_decorator(csrf_exempt,name='dispatch')  # 可以
class MyIndex(views.View):
    # @method_decorator(csrf_exempt)  # 可以
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request,*args,**kwargs)
    def get(self,request):
        return render(request,'transfer.html')
    # @method_decorator(csrf_exempt,name='post')  # csrf_exempt不支持该方法
    def post(self,request):
        return HttpResponse('OK')   

# @method_decorator(csrf_protect,name='post')  # 可以
class MyIndex(views.View):
    @method_decorator(csrf_protect)  # 可以
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request,*args,**kwargs)
    def get(self,request):
        return render(request,'transfer.html')
    # @method_decorator(csrf_protect)  # 可以
    def post(self,request):
        return HttpResponse('OK')

Three, Django auth management

Django Auth module is built-in user authentication module.

There django login authentication to help us do a lot of things you do not have to write their own, really happy too!

User data is stored in data migration, Django automatically help auth_user table we created.

1. auth module common method

1.1 Creating a User

Auth want to use to create a user need to start django.contrib.auth.modelsimporting usermodule:

from django.contrib.auth.models import User

# 不可用  密码不是加密的
# User.objects.create(username=username,password=password)

# 创建普通用户    密码自动加密
User.objects.create_user(username=username,password=password) 

# 创建超级用户   需要邮箱数据  密码自动加密
User.objects.create_superuser(username=username,password=password,email='[email protected]')  


# 源码
def create_user(self, username, email=None, password=None, **extra_fields):
    extra_fields.setdefault('is_staff', False)
    extra_fields.setdefault('is_superuser', False)
    return self._create_user(username, email, password, **extra_fields)

def create_superuser(self, username, email, password, **extra_fields):
    extra_fields.setdefault('is_staff', True)
    extra_fields.setdefault('is_superuser', True)

1.2 validate the user name and password

Want to use the auth check your username and password required to start django.contribimporting authmodule:

from django.contrib import auth

user_obj = auth.authenticate(request,username=username,password=password)
# 必须传用户名和密码两个参数 缺一不可

If the user does not find the user_obj return none.

1.3 to save the user login status

Use auth.login(request,user_obj)to save the user login status, automatically recorded in user_session table.

def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user_obj = auth.authenticate(request,username=username,password=password)
        # print(user_obj)
        if user_obj:
            # print(user_obj)
            # print(type(user_obj))
            # 保存用户登录状态,在session表中保存用户
            # 相当于request.session['user'] = 'name'
            # 且只要执行了这一句话,
            # 之后你可以在任意位置通过request.user获取到当前登录用户对象
            auth.login(request,user_obj)
            return HttpResponse('登陆成功!')

    return render(request,'login.html')

1.4 determine whether the current user login

Use request.user.is_authenticated()determine whether the user is logged in, it returns a Boolean value, True / False.

def check_login(request):
    if request.user.is_authenticated():
        return HttpResponse('login')
    else:
        return HttpResponse('not login')

1.5 verify the original password is correct

Through request.user.check_password(旧密码)to verify whether the user has entered the correct password, it returns a Boolean value True / False.

@login_required # 局部登录跳转页面配置
def check_password(request):
    user_obj = request.user  # 获取已经登陆的用户
    if request.method == 'POST':
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        # 校验原来的密码是否正确 返回布尔
        is_right = user_obj.check_password(old_password)
        if is_right:
            user_obj.set_password(new_password)
            user_obj.save()
        return HttpResponse('修改成功!')
    return render(request,'change_password.html')

1.6 Change Password

By request.user.set_password(新密码)modifying the user's password, you need to be performed after completion of modification request.user.save()to the modified data into the database.

Otherwise, data is only modified a bit in the cache, not really written to the database.

@login_required # 局部登录跳转页面配置
def check_password(request):
    user_obj = request.user  # 获取已经登陆的用户
    if request.method == 'POST':
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        # 校验原来的密码是否正确 返回布尔
        is_right = user_obj.check_password(old_password)
        if is_right:
            # 修改用户密码,并保存
            user_obj.set_password(new_password)
            user_obj.save()
        return HttpResponse('修改成功!')
    return render(request,'change_password.html')

1.7 Logout

Directly auth.logout(request)log the user out method.

@login_required
def logout(request):
    auth.logout(request)
    return HttpResponse('用户已注销!')

1.8 verify whether the user is logged decorator

1. First you need to import login authentication function decorator module

from django.contrib.auth.decorators import login_required

2. Then jump to the url login page can be set when not logged in

Local Configuration

@login_required(login_url='/login/')
def func(request):
    pass

Global Configuration (settings configuration file directly to configure)

# settings中配置
LOGIN_URL = '/login/'

# views
@login_required  
def func(request):
    pass

note:

If the global configuration, and also local configuration, will be localized login_urlprevail.

2. The extended fields in the table auth_user

2.1 use one table to establish a foreign key relationship

Write a table to another field stores to be added, with one foreign key relationships bound to auth_user table.

Prior to need to bind the from django.contrib.auth.models import Usertable guide created automatically come.

# models
from django.contrib.auth.models import User
class UserDetail(models.Model):
    phone = models.BigIntegerField()
    user = models.OneToOneField(to='User')

2.2 auth class inherits provided by Django

This should have auth_user directly modify the table before you create all the tables.

By inheriting the parent class User table rewrite their own new User class.

Prior to inherit the same parent needs to User from django.contrib.auth.models import AbstractUserguide over.

# models
from django.contrib.auth.models import AbstractUser
class Userinfo(AbstractUser):
    phone = models.BigIntegerField()
    register_time = models.DateField(auto_now_add=True)

note:

After rewriting their own class, you need to configure it in the configuration file, otherwise the system does not know what you want yourself to rewrite the table.

After writing, before all the auth module functions can also be used by all your new writing table.

# settings
AUTH_USER_MODEL = 'app01.Userinfo'  # 应用名.表名

Guess you like

Origin www.cnblogs.com/bowendown/p/12004040.html