django之用户认证组件

功能:用session记录登陆验证状态

前提:用户表:django自带的auth_user

创建超级用户:python manage.py createsuperuser

本质也是用的django-session,不过人家这个更严谨,更新账户的时候连着session_key一起换了。

基于用户认证组件的登录验证信息储存和注销

views.py

from django.shortcuts import render, HttpResponse, redirect

# Create your views here.

from django.contrib import auth
from django.contrib.auth.models import User


def login(request):
    if request.method == 'POST':
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')

        # if 验证成功user对象,else返回none
        user = auth.authenticate(username=user, password=pwd)

        if user:
            auth.login(request, user)  # request.user:当前登录对象。如果没有登录,就是匿名登录对象

            return redirect('/index/')

    return render(request, 'login.html')


def index(request):
    print('request user', request.user.username)  # request user  # 登录成功: request user edward
    print(request.user.id)  # None    # 登录成功:1
    print(request.user.is_anonymous)  # True   #  登录成功:False

    # if request.user.is_anonymous:
    if not request.user.is_authenticated:
        return redirect('/login/')

    return render(request, 'index.html')

def logout(request):
    auth.logout(request)

    return redirect('/login/')

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>

<!--  request.user是全局变量,可以直接在模板里面用 -->

<h3>Hi, {{ request.user.id }}- {{ request.user.username }} </h3>
<a href="/logout">注销</a>
    
</body>
</html>

 

注册用户组件

def reg(request):
    if request.method == 'POST':
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')

        # User.objects.create(username=user,password=pwd)  # 不要用这种方法,这种方法是按照明文插入的
        user = User.objects.create_user(username=user, password=pwd)

        return redirect('/login/')
    return render(request, 'reg.html')

 

reg.html

<h3>注册</h3>
<form action="" method="post">
    {% csrf_token %}
    <p>用户名:<input type="text" name="user"></p>
    <p>密码: <input type="text" name="pwd"></p>
    <input type="submit" value="提交">
</form>

 

API

from django.contrib import auth:

  1. if 验证成功user对象,else返回None

    user = auth.authenticate(username=user,password=pwd)

  2. auth.login(request, user) # request.user:当前登录对象。如果没有登录,就是匿名登录对象。

  3. auth.logout(request)

from django.contrib.auth.models import User

  1. requeset.user.is_authenticated

  2. user = User.objects.create_user(username='', password='',email='')

补充

匿名用户对象

 匿名用户
    class models.AnonymousUser

    django.contrib.auth.models.AnonymousUser 类实现了django.contrib.auth.models.User 接口,但具有下面几个不同点:

    id 永远为None。
    username 永远为空字符串。
    get_username() 永远返回空字符串。
    is_staff 和 is_superuser 永远为False。
    is_active 永远为 False。
    groups 和 user_permissions 永远为空。
    is_anonymous() 返回True 而不是False。
    is_authenticated() 返回False 而不是True。
    set_password()、check_password()、save() 和delete() 引发 NotImplementedError。
    New in Django 1.8:
    新增 AnonymousUser.get_username() 以更好地模拟 django.contrib.auth.models.User。

 

修改密码

user = User.objects.get(username='')
user.set_password(password='')
user.save 

 

@login_required
def set_password(request):
    user = request.user
    state = None
    if request.method == 'POST':
        old_password = request.POST.get('old_password', '')
        new_password = request.POST.get('new_password', '')
        repeat_password = request.POST.get('repeat_password', '')
        if user.check_password(old_password):
            if not new_password:
                state = 'empty'
            elif new_password != repeat_password:
                state = 'repeat_error'
            else:
                user.set_password(new_password)
                user.save()
                return redirect("/log_in/")
        else:
            state = 'password_error'
    content = {
        'user': user,
        'state': state,
    }
    return render(request, 'set_password.html', content)

 

总结

if not : auth.login(request, user) request.user = AnonymousUser( )

else : request.user == 登录对象

request.user是一个全局变量,在任何视图和模板都可以直接使用。

 

于用户认证组件的认证装饰器

django为我们设计了一个用于检查用户是否已经通过了认证:login_requierd()

 

views.py

from django.contrib.auth.decorators import login_required

@login_required
def index(request):
    # print('request user', request.user.username)  # request user  # 登录成功: request user edward
    # print(request.user.id)  # None    # 登录成功:1
    # print(request.user.is_anonymous)  # True   #  登录成功:False
    #
    # # if request.user.is_anonymous:
    # if not request.user.is_authenticated:
    #     return redirect('/login/')

    return render(request, 'index.html')

@login_required
def order(request):
    # if not request.user.is_authenticated:
    #     return redirect('/login/')

    return render(request, 'order.html')
def login(request):
    if request.method == 'POST':
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')

        # if 验证成功user对象,else返回none
        user = auth.authenticate(username=user, password=pwd)

        if user:
            auth.login(request, user)  # request.user:当前登录对象。如果没有登录成功,就是匿名登录对象

            # http://127.0.0.1:8000/login/?next=/index/
            next_url = request.GET.get('next', "/index/")
            # 动态获取next后面的url(设置在settings.py里面,也就是跳转到哪里的路径),如果取不到就用/index/

            return redirect(next_url)

    return render(request, 'login.html')

 

settings.py

LOGIN_URL = '/login/'  # 跳转路径

 

 

 

posted @ 2019-02-04 17:38  梁少华  阅读(226)  评论(0编辑  收藏  举报