[py][mx]django自定义认证类

Posted 毛台

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[py][mx]django自定义认证类相关的知识,希望对你有一定的参考价值。

创建自定义验证用户名密码类CustomBackend

users/views.py

from django.contrib.auth import authenticate, login
from django.contrib.auth.backends import ModelBackend
from django.shortcuts import render

# Create your views here.
from users.models import UserProfile


class CustomBackend(ModelBackend):  # 继承认证类,diy它
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:  # 验证用户名密码 否则返回None
            user = UserProfile.objects.get(username=username)  # 表示有这个用户 查处自定义usermodel的用户名,
            if user.check_password(password):  # 表示这个用户密码正确, 这里django存储密码是加密的,必须用其下这个方法加密后比对是否正确
                return user
        except Exception as e:
            return None  # 密码错误返回None


def user_login(request):
    if request.method == "POST":
        user_name = request.POST.get("username", "")
        pass_word = request.POST.get("password", "")
        user = authenticate(username=user_name, password=pass_word)
        if user is not None:  # 用户名密码验证成功
            login(request, user)  # django执行用户登录
            return render(request, "index.html")
        else:
            return render(request, "index.html", {})

    elif request.method == "GET":
        return render(request, "login.html", {})

users/settings.py

AUTH_USER_MODEL = "users.UserProfile"
AUTHENTICATION_BACKENDS = (\'users.views.CustomBackend\',)

断点调试, 确实已经用了我们自定义的认证类.

允许用户名用邮箱登录

且的关系
user = UserProfile.objects.get(username=username,email=username) 


或的关系: django自带了Q实现
from django.db.models import Q

user = UserProfile.objects.get(Q(username=username) | Q(email=username)) 

users/views.py完整的

from django.contrib.auth import authenticate, login
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

class CustomBackend(ModelBackend):  # 继承认证类,diy它
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:  # 验证用户名密码 否则返回None
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))  # 表示有这个用户 查处自定义usermodel的用户名,
            if user.check_password(password):  # 表示这个用户密码正确, 这里django存储密码是加密的,必须用其下这个方法加密后比对是否正确
                return user
        except Exception as e:
            return None  # 密码错误返回None

前端输错用户名密码错误提示

users/views.py

def user_login(request):
    if request.method == "POST":
        user_name = request.POST.get("username", "")
        pass_word = request.POST.get("password", "")
        user = authenticate(username=user_name, password=pass_word)
        if user is not None:  # 用户名密码验证成功
            login(request, user)  # django执行用户登录
            return render(request, "index.html")
        else:
            return render(request, "login.html", {\'msg\':"用户名或密码错误"})

    elif request.method == "GET":
        return render(request, "login.html", {})

templates/login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body>
<div>
    <form action="/login/" method="post">
        <p><input type="text" name="username" placeholder="username"></p>
        <p><input type="text" name="password" placeholder="password"></p>
        <p><input type="submit"></p>
        {% csrf_token %}
    </form>
    {{ msg }}
</div>
</body>
</html>

以上是关于[py][mx]django自定义认证类的主要内容,如果未能解决你的问题,请参考以下文章

[py]django项目-让系统用自定义的users表认证

自定义authenticate()认证方法 | Django

[py][mx]django使用class写views-免去判断方法的烦恼

Django(64)频率认证源码分析与自定义频率认证

西游之路——python全栈——自定义用户认证

Django自定义Auth模块方式