Django -为带有AbstractUser继承的登录添加额外子句

wko9yo5t  于 2023-03-04  发布在  Go
关注(0)|答案(1)|浏览(87)

我有以下型号:
employee.py

class Employee(auth_models.AbstractUser, MetadataModel):
    user = models.CharField(unique=True, primary_key=True)
    first_name = models.CharField(blank=True, null=True)
    last_name = models.CharField(blank=True, null=True)
    is_deleted = models.BooleanField(default=False)

我的settings.py引用Employee模型进行身份验证:AUTH_USER_MODEL = 'core.Person'
默认情况下,is_active=True时用户只能使用AbstractUser模型登录,如何更改此条件,使身份验证为:is_active==Trueis_deleted==FalseEmployee中保留对AbstractUser的继承?

sauutmhj

sauutmhj1#

您可以为此编写一个自定义身份验证后端,如下所示:

from django.contrib.auth.backends import BaseBackend
from django.contrib.auth.hashers import check_password

class MyBackend(BaseBackend):
    def authenticate(self, request, username=None, password=None):
        # Check the username/password and return a user.
        try:
            user = Employee.objects.get(username=username, is_active=True,is_deleted=False)
            if check_password(password, user.password):
                  return user
         except Employee.DoesNotExist():
             return None
         return None

然后在settings.py中添加这个新后端:

AUTHENTICATION_BACKENDS =  ['yourapp.auth_backend.MyBackend']

相关问题