用户认证组件auth

django有自带的用户认证组件:自动用session记录登陆验证状态,将用户名和密码表存在了dajngo自带的auth_user里。

  用户表:dajngo自带的auth_user
  (不在models里创建表,直接做数据库迁移,查看数据库由auth_user表)
  控制台创建超级用户:python3 manage.py createsuperuser

主要语法:

  • auth模块:from django.contrib import auth
authenticate()   
	提供了用户认证,即验证用户名以及密码是否正确
	user=auth.authenticate(username=user,password=pwd)

login(HttpRequest, user) 

	该函数接受一个HttpRequest对象,以及一个认证了的User对象
	此函数使用django的session框架给某个已认证的用户附加上session id等信息。
	auth.login(request,user)
	
logout(request) 注销用户
	# 注销
	def logout(request):
  	  	auth.logout(request)
    	return redirect("/login/")
  • User对象from django.contrib.auth.models import User
 is_authenticated
 	通过认证这只是表明用户成功的通过了认证。
 	创建用户

create_user 
	辅助函数创建用户:
	user = User.objects.create_user(username='',password='',email='')
	
check_password(passwd)
	用户需要修改密码的时候,首先要让其输入原来的密码 ,
	如果给定的值通过了密码检查,返回 True

set_password() 
	来修改密码
	user = User.objects.get(username='')
	user.set_password(password='')
	user.save()
  • 自定义user表

https://www.cnblogs.com/liwenzhou/p/9030211.html

示例:

from django.shortcuts import render,HttpResponse,redirect

# Create your views here.

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

def login(request):

    if request.method == "POST":
        user = request.POST.get("user")
        pwd = request.POST.get("pwd")

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

        if user:
            auth.login(request,user)   # 设置了request.user对象,重点。就是当前登录对象
            '''
             # request.user  =  当前登录对象 , 
            没有登录 取出来得是匿名用户(AnonymousUser)
            session表里的 session-id session-data 一个浏览器,不同得用户,两个字段都会变
            自己写得session session-id 不会变 不同用户,同一浏览器,只会变session-data
            '''

            # return redirect("/index/")

            next_url=request.GET.get("next","/index/")
            return redirect(next_url)


    return render(request,"login.html")



@login_required
def index(request):

    print("request.user:", request.user)
    # 没有登陆的话就是显示匿名用户对象,reuqest属性参考视图层里所讲
    print("request.user:",request.user.id)
    print("request.user:",request.user.is_anonymous)

    # 所以用匿名用户对象request属性可以判断当前用户是否是已登陆
    # 方式一:request.user.is_anonymous

    if request.user.is_anonymous:
        return redirect("/login/")

    # username = request.user.username
    # return render(request,"index.html",{"username":username})
    # 不用再传值,request.user是全局,模板层html也可以直接用
    # 

Hi,{{ request.user.username }}

return render(request, "index.html") # 方式二: if not request.user.is_authenticated: return redirect("/login/") # 方式三: ''' 装饰器 @login_required 注意下settings设置里的login_url 注意下login函数的返回值:return next_url=request.GET.get("next","/index/") return redirect("/index/")不能固定写, 加了装饰器如果没有登陆执行某视图函数时会跳转到login函数,同时路径里会拼接“?next+试图函数路径” # http://127.0.0.1:8000/login/?next=/index/ 所以login不能固定返回某页面,而是返回request里的拼接路径 ''' 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 logout(request): auth.logout(request) return redirect("/login/") # 注册功能 def reg(request): if request.method=="POST": user = request.POST.get("user") pwd = request.POST.get("pwd") # User是auth引入的,存储密码是密文 # 不能用这个 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")

index




Hi,{{ request.user.username }}

注销

修改密码:

@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)

注册:

def sign_up(request):

    state = None
    if request.method == 'POST':

        password = request.POST.get('password', '')
        repeat_password = request.POST.get('repeat_password', '')
        email=request.POST.get('email', '')
        username = request.POST.get('username', '')
        if User.objects.filter(username=username):
                state = 'user_exist'
        else:
                new_user = User.objects.create_user(username=username, password=password,email=email)
                new_user.save()

                return redirect('/book/')
    content = {
        'state': state,
        'user': None,
    }
    return render(request, 'sign_up.html', content)

你可能感兴趣的:(django)