首页 > 其他分享 >11 Auth认证模块

11 Auth认证模块

时间:2023-02-13 07:44:17浏览次数:42  
标签:11 py request Auth user 模块 login password auth

Auth认证模块

Auth模块是什么

Auth模块是Django自带的用户认证模块:

在开发一个网站的时候,无可避免的需要设计实现网站的用户系统。此时需要实现包括用户注册、登录、认证、注销、修改密码等功能

django内置了强大的用户认证系统--auth,默认使用 auth_user 表来存储用户数据

如果用了auth模块那么就用全套

auth模块常用方法

from django.contrib import auth

命令行创建超级用户

Tools -> Run manage.py Task: createsuperuser (Email address可以为空) 超级用户有登陆django admin后台管理的权限

用户创建后会更新到auth_user表中

authenticate(username='',password='')

提供了用户认证功能,即验证用户名以及密码是否正确,username 、password两个关键字参数不能少。认证成功便会返回一个 User 对象。

user_obj = auth.authenticate(username='jason',password='123')

login(HttpRequest, user)

HttpRequest: HttpRequest对象

user: 经过认证的User对象

会在后端为该用户生成相关session数据更新到django_session表中,并且可以在后端任意位置通过request.user获取到当前用户对象,否则request.user拿到的是匿名用户。

from django.contrib.auth import authenticate, login
   
def login(request):
    username = request.POST['username']
    password = request.POST['password']
    user_obj = authenticate(username=username, password=password)
    if user is not None:
        login(request, user)
        # Redirect to a success page.
        ...
    else:
        # Return an 'invalid login' error message.
        ...

**logout(request) **

该函数接受一个HttpRequest对象,无返回值。

当调用该函数时,当前请求的session信息会全部清除。即使没有登录,使用该函数也不会报错。

from django.contrib.auth import logout
   
def logout(request):
    logout(request)  # 等价于 request.session.flush()
    # Redirect to a success page.

is_authenticated

用来判断当前请求是否通过了认证,即判断用户是否登陆,如果是匿名用户则返回False。

dkdef test(request):
    print(request.user)  # 没有执行auth.login则拿到的是匿名用户
	if not request.user.is_authenticated:
	    return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))

@login_requierd(login_url='')

登录校验装饰器。自动校验是否登录,没有登录则跳转到login_url指定的登陆页面,并传递当前访问的url(http://127.0.0.1:8000/login/?next=/index/)

from django.contrib.auth.decorators import login_required

# 方式一:局部配置
@login_required(login_url='/login')
def index(request):
    pass

# 方式二:全局配置
"""
# settings.py中配置项目登录页面的路由
    LOGIN_URL = '/login/'
"""
@login_required
def index(request):
    pass

create_user(username='',password='',...)

auth提供的一个创建新用户的方法,必传字段username、password

from django.contrib.auth.models import User

user_obj = User.objects.create_user(username='jason',password='123',email='[email protected]',...)

create_superuser(username='',password='',...)

auth 提供的一个创建新的超级用户的方法,必传字段username、password

from django.contrib.auth.models import User

user_obj = User.objects.create_superuser(username='jason',password='123',email='[email protected]',...)

check_password(password)

auth提供的一个检查密码是否正确的方法,密码正确返回True,否则返回False。

is_right = request.user.check_password('password')

set_password(password)

auth提供的一个修改密码的方法,设置完一定要调用用户对象的save方法

request.user.set_password('new_password')
request.user.save()

修改密码示例:

from django.contrib.auth.decorators import login_required

"""
# settings.py中配置项目登录页面的路由
    LOGIN_URL = '/login/'
"""
@login_required
def set_password(request):
    user = request.user
    err_msg = ''
    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:
                err_msg = '新密码不能为空'
            elif new_password != repeat_password:
                err_msg = '两次密码不一致'
            else:
                user.set_password(new_password)
                user.save()
                return redirect("/login/")
        else:
            err_msg = '原密码输入错误'
    content = {
        'err_msg': err_msg,
    }
    return render(request, 'set_password.html', content)

User对象的属性

User对象属性:username, password

is_staff:用户是否拥有网站的管理权限

is_active:是否允许用户登录, 设置为False可以在不删除用户的前提下禁止用户登录

扩展默认的auth_user表

内置的auth_user表字段都是固定的,无法扩展字段

方式一:新建另外一张表然后通过一对一和内置的auth_user表关联

方式二:通过继承内置的AbstractUser类来定义一个自己的Model类,注意扩展的字段不能跟原auth_user表字段重复

from django.contrib.auth.models import AbstractUser

class UserInfo(AbstractUser):
    nid = models.AutoField(primary_key=True)
    phone = models.CharField(max_length=11, null=True, unique=True)

一定要在settings.py中告诉Django使用新定义的UserInfo表来做用户认证

AUTH_USER_MODEL = "app名.UserInfo"  # 应用名.model类名

执行数据库迁移命令后,会在数据库中创建该表app01_userinfo,之后所有的auth模块功能都基于新创建的表app01_userinfo而不再是auth_user

参考django中间件源码实现settings功能插拔式源码

目录结构:

"""
notify文件夹
​    __init__.py
​    email.py
​    msg.py
​    qq.py
​    wechat.py
settings.py
start.py
"""

email.py、msg.py、qq.py、wechat.py

# email.py
class Email(object):
    def __init__(self):
        pass
    def send(self, content):
        print('邮件通知: %s' % content)
        

# msg.py
class Msg(object):
    def __init__(self):
        pass
    def send(self, content):
        print('短信通知: %s' % content)
        
        
# qq.py
class QQ(object):
    def __init__(self):
        pass
    def send(self, content):
        print('qq通知: %s' % content)

# wechat.py
class WeChat(object):
    def __init__(self):
        pass
    def send(self, content):
        print('微信通知: %s' % content)

__init__.py

import settings
import importlib

def send_all(content):
    for path_str in settings.NOTIFY_LIST:
        module_path, class_name = path_str.rsplit('.', maxsplit=1)
        module = importlib.import_module(module_path)
        cls = getattr(module, class_name)
        obj = cls()
        obj.send(content)

settings.py

NOTIFY_LIST = [
    'notify.email.Email',
    'notify.msg.Msg',
    # 'notify.wechat.WeChat',  # 直接再settings.py中通过打开/关闭注释开启/关闭某个功能
    'notify.qq.QQ'
]

start.py

import notify

if __name__ == '__main__':
    notify.send_all('国庆7天假去哪玩?')

标签:11,py,request,Auth,user,模块,login,password,auth
From: https://www.cnblogs.com/jlllog/p/17115187.html

相关文章

  • 代码随想录算法Day11 | 20. 有效的括号,1047. 删除字符串中的所有相邻重复项,逆波兰表达
     20.有效的括号题目链接: 20.有效的括号-力扣(LeetCode)题目给定一个只包括'(',')','{','}','[',']' 的字符串s,判断字符串是否有效。有效字符串需满足:左括号必须用......
  • 【题解】P3711 仓鼠的数学题
    poly令人晕眩,令人晕眩的poly.思路伯努利数。首先意识到有一个拉插题也是求自然数幂和,所以答案是关于\(n\)的\(k\)次多项式。考虑设出\(S_{n,k}=\sum\limits_......
  • 学习笔记jira项目23useauth切换登录和非登录信息
    importReact,{useState}from"react";import{RegisterScreen}from"unauthenticated-app/register";import{LoginScreen}from"unauthenticated-app/login";im......
  • 学习笔记jira项目21-jwt原理和auth-provide
    constAuthContext=React.createContext<|{user:User|null;register:(form:AuthForm)=>Promise<void>;login:(form:AuthForm)=>Promise<......
  • 力扣---1138. 字母板上的路径
    我们从一块字母板上的位置(0,0)出发,该坐标对应的字符为board[0][0]。在本题里,字母板为board=["abcde","fghij","klmno","pqrst","uvwxy","z"],如下所示。我们可......
  • salt2-11
    SaltStack安装基础环境准备基于centos6和centos7的差异,在两个不同的操作系统中安装saltstack也是不一样的。Centos6需要先安装扩展源,然后在进行安装:Master端yuminstall......
  • python优缺点分析11
    学--就如同你即将看到的一样,Python极其容易上手。前面已经提到了,Python有极其简单的语法。​ 免费、开源--Python是FLOSS(自由/开放源码软件)之一。简单地说,你可以自......
  • x210-2023-02-11
    1、secureCRT中文不乱码,而英文有部分出现乱码,譬如下面图中乱码位置正常应该显示的是asm,但是其余英文并没有乱码,会话选项的字体原来设置的是新宋体,字符编码为默认,字符集为GB......
  • CF1167G题解
    CF1167G题解传送门简化题意:数轴上有n个不相交且处于坐标为非负整数的单位正方形,给m个询问点,求出把这个点右侧的数轴逆时针旋转至与左侧相交时的角度。首先,碰撞时只......
  • ansible的部署和命令模块
    一、ansible的概述1、ansible简介Ansible是一款为类Unix系统开发的自由开源的配置和自动化工具。它用Python写成,类似于saltstack和Puppet,但是有一个不同和优点是我们......