[1101 | Day58] Auth authentication module

auth module

After completion of cookie and session, although before we can resolve to save the user login information function, but by writing a decorator, take the way in the use of header information check returned, I still feel a little trouble.

Is there a way to be able to save something, ah, for cancer patients depth lazy, if someone can give me a good package just fine! ! !

Ha ha ha ha, sure enough, python expectations by as early as you do a good job, only you think, no it can not, this is python gospel learners.

Next, we opened with the magic of mystery --Auth module.

Create a super administrator

Super User: login for django admin background management

createsuperuser

Check whether the user exists

user_obj = auth.authenticate(username=username,password=password)  
# 返回的是数据对象  没有返回None 比如返回的是Jason,其实里面含有username、age等,可以通过点取值

note! ! !

username=username,password=password

These two parameters must be, can not write only one.

1572492323301

Save the user login status

auth.login(request,user_obj)  # 执行完这一句之后 主要是能够拿到request的地方 
# 都可以通过request.user获取到当前登录用户对象

Determine whether the current user login

request.user.is_authenticated()  #存在返回True,不存在返回False

Gets the current user data object

request.user

Check whether the login decorator

When the user is not logged url jump in two configurations

  • Specified by local decorator login_url parameters within the brackets
  • The case of global configuration user is not logged unified view of all the jump to a url, profileLOGIN_URL = '/login/'
from django.contrib.auth.decorators import login_required

# @login_required(login_url='/xxx/')  # 局部配置
@login_required  # 全局配置
def home(request):
return HttpResponse('home页面')

change Password

Check the original password is correct

is_right = request.user.check_password(old_password)

A new password

request.user.set_password(new_password)
request.user.save()   #记得一定要使用save()方法

User Registration

from django.contrib.auth.models import User

#User.objects.create(username=username, password=password)  # 不用使用create 密码会直接存成明文
User.objects.create_user(username=username,password=password)  # 创建普通用户
User.objects.create_superuser(username=username,password=password,email='[email protected]')  # 创建超级用户  邮箱字段必须填写

Extension field auth_user table

The first step: to write a dictation class that inherits the original class auth_user

from django.db import models
from django.contrib.auth.models import AbstractUser

class Userinfo(AbstractUser):
    """
    强调 继承了AbstractUser之后 你自定义的表中 字段不能跟原有的冲突
    """
    phone = models.BigIntegerField()
    avatar = models.FileField()
    register_time = models.DateField(auto_now_add=True)

Step Two: In the settings configuration file settings tell django to use the new class as an alternative auth_user table

#固定语法: AUTH_USER_MODEL = '应用名.表名'

AUTH_USER_MODEL = 'app01.Userinfo'

auth implement user login register

from django.shortcuts import render, HttpResponse, redirect, reverse
from django.contrib import auth
from django.contrib.auth.models import User

# Create your views here.
#登录
def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        #models.User.objects.filter(username=username,password=password).first()
        user_obj = auth.authenticate(username=username, password=password)
        """
        该方法会有一个返回值  当条件存在的情况下 返回就是数据对象本身
        条件不满足 直接返回None
        """
        if user_obj:
            # 一定要记录用户状态 才算真正的用户登录
            request.session['user'] = user_obj
            auth.login(request, user_obj)
            """该方法会主动帮你操作session表 并且只要执行了该方法
             你就可以在任何位置通过request.user获取到当前登录的用户对象
            """
            old_path = request.GET.get('next')
            if old_path:
                return redirect(old_path)
            else:
                return redirect('/home/')
    return render(request, 'login.html')


def index(request):
    print(request.user)  # 直接拿到登录用户的用户对象
    print(request.user.is_authenticated())  # 简单快速地判断用户是否登录
    return HttpResponse('index')


from django.contrib.auth.decorators import login_required

# @login_required(login_url='/login/')  # 局部配置
@login_required  #全局配置
def set_password(request):
    if request.method == 'POST':
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        # 校验原密码对不对
        is_right = request.user.check_password(old_password)
        # print(is_right)
        if is_right:
            # 修改密码
            request.user.set_password(new_password)  # 仅仅只会在内存中产生一个缓存 并不会直接修改数据库
            request.user.save()  # 一定要点save方法保存 才能真正的操作数据库
            return redirect('/login/')
    return render(request, 'set_password.html', locals())


# @login_required(login_url='/xxx/')
@login_required
def home(request):
    return HttpResponse('home页面')


def register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        # User.objects.create(username=username,password=password)  # 不能直接使用create 密码会直接存成明文
        # User.objects.create_user(username=username,password=password)  # 创建普通用户
        User.objects.create_superuser(username=username, password=password, email='[email protected]')  # 创建超级用户  邮箱字段必须填写

    return render(request, 'register.html')

On completion of Auth module, python have not found the language more convenient!

Guess you like

Origin www.cnblogs.com/fxyadela/p/11774924.html