11 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='jason@qq.com',...)

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='jason@qq.com',...)

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天假去哪玩?')

posted @   生姜J  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
返回顶端
点击右上角即可分享
微信分享提示