如何更改django检查其他布尔字段而不是is_staff进行管理面板身份验证?

时间:2019-05-21 17:30:31

标签: django django-admin custom-authentication

我具有以下自定义“ AUTH_USER_MODEL”:

class User(AbstractUser):
    is_institute_admin = models.BooleanField(default=False)

    def has_perm(self, perm, obj=None):
        app_label = perm.split('.')[0]
        if self.is_institute_admin:
            return app_label == 'Profiler'
        if self.is_superuser:
            return app_label == 'Accountant'

    def has_module_perms(self, app_label):
        if self.is_institute_admin:
            return app_label == 'Profiler'
        if self.is_superuser:
            return app_label == 'Accountant'

我希望当用户登录django管理面板时,身份验证必须检查is_institute_admin而不是默认情况下的is_staff

我在settings.py中添加并注册了一个自定义身份验证文件,如下所示:

class CustomBackend:

    def authenticate(self, request, username=None, password=None):
        try:
            user = User.objects.get(username=username)
            print('user value =', user, password)

            password_valid = check_password(password=password, encoded=user.password)
            if password_valid:
                if user.is_superuser or user.is_institute_admin:
                    print('returning user')
                    return user
                return None
            else:
                print('password not matched')
                return None
        except User.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

关于调试,我添加了一些打印语句,它打印到print('returning user')为止,但是身份验证失败。

谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

这与auth后端无关,但与用户模型有关。该模型始终需要一个is_staff属性,但是可以想象该属性可以返回其他字段的值:

class User(AbstractUser):
    is_institute_admin = models.BooleanField(default=False)

    @property
    def is_staff(self):
        return self.is_institute_admin

尽管我必须说,将字段保留为is_staff并更改相关表格上的标签会更容易。