0
我使用AbstractBaseUser類創建了自定義用戶模型。代碼相同在這裏。無法在Django中使用自定義身份驗證後端
class UserModel(AbstractBaseUser):
user_type_choices = (
(constants.USER_TYPE_ADMIN, 'Admin'),
(constants.USER_TYPE_INSTITUTE, 'Institute'),
(constants.USER_TYPE_STUDENT, 'Student')
)
sys_id = models.AutoField(primary_key=True, blank=True)
name = models.CharField(max_length=127, null=False, blank=False)
email = models.EmailField(max_length=127, unique=True, null=False, blank=False)
mobile = models.CharField(max_length=10, unique=True, null=False, blank=False)
user_type = models.PositiveSmallIntegerField(choices=user_type_choices, null=False, blank=True, help_text="Admin(1)/Institute(2)/Student(3)")
access_valid_start = models.DateTimeField(null=True, blank=True)
access_valid_end = models.DateTimeField(null=True, blank=True)
created_when = models.DateTimeField(null=True, blank=True)
created_by = models.BigIntegerField(null=True, blank=True)
last_updated_when = models.DateTimeField(null=True, blank=True)
last_updated_by = models.BigIntegerField(null=True, blank=True)
notes = models.CharField(max_length=2048, null=True, blank=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=True)
objects = MyUserManager()
USERNAME_FIELD = "email"
# REQUIRED_FIELDS must contain all required fields on your User model,
# but should not contain the USERNAME_FIELD or password as these fields will always be prompted for.
REQUIRED_FIELDS = ['name', 'mobile', 'user_type']
class Meta:
app_label = "accounts"
db_table = "users"
def __str__(self):
return self.email
def get_full_name(self):
return self.name
def get_short_name(self):
return self.name
def is_access_valid(self):
if self.access_valid_end > utility.now():
return True
else:
return False
def save(self, *args, **kwargs):
if not self.sys_id:
self.created_when = utility.now()
self.last_updated_when = utility.now()
return super(UserModel, self).save(*args, **kwargs)
其經理的代碼如下。
class MyUserManager(BaseUserManager):
use_in_migrations = True
def create_user(self, email, name, mobile, user_type, password):
return create_superuser(self, email, name, mobile, user_type, password)
# python manage.py createsuperuser
def create_superuser(self, email, name, mobile, user_type, password):
user = self.model(
email = email,
name = name,
mobile = mobile,
user_type = user_type,
access_valid_start = utility.now(),
access_valid_end = utility.get_access_end_date(),
created_when = utility.now(),
created_by = constants.COMMAND_LINE_USER_ID,
last_updated_when = utility.now(),
last_updated_by = constants.COMMAND_LINE_USER_ID,
notes = 'This user is created from command line. createsuperuser utility.'
)
user.set_password(password)
user.save(using=self._db)
return user
我也創建了認證後端。
class MyAuthBackend(object):
def authenticate(self, email, password):
try:
user = UserModel.objects.get(email=email)
if user.check_password(password):
return user
else:
return None
except UserModel.DoesNotExist:
logging.getLogger("error_logger").error("user with login %s does not exists " % login)
return None
except Exception as e:
logging.getLogger("error_logger").error("user with login %s does not exists " % login)
return None
def get_user(self, user_id):
# user_id must be the primary key of table.
try:
user = UserModel.objects.get(sys_id=user_id)
if user.is_active:
return user
return None
except UserModel.DoesNotExist:
logging.getLogger("error_logger").error("user with %(user_id)d not found")
return None
我已經在設置文件中包含了自定義用戶模型和後端。
AUTH_USER_MODEL = 'accounts.UserModel'
AUTHENTICATION_BACKENDS = ('accounts.backends.MyAuthBackend',)
我創建命令行超級用戶,但是當我試圖從管理員登錄的網址登錄,下面的錯誤被拋出。
Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive.
如建議在this SO answer,我用後備認證後端,然後它開始拋出這個錯誤:'UserModel' object has no attribute 'has_module_perms'
。這意味着後備後端在這裏工作。但它需要在自定義用戶模型中添加以下功能。
def has_perm(self, perm, obj=None):
return self.is_superuser
# this methods are require to login super user from admin panel
def has_module_perms(self, app_label):
return self.is_superuser
並添加了is_superuser字段。現在它工作正常。
因此,我有以下問題:
- 爲什麼我不能夠嘗試從管理面板登錄時使用自定義的後端驗證用戶?
- 爲什麼函數has_perm,
is_staff
和is_superuser
字段對於從管理面板登錄是強制性的? - 爲什麼從我自己的登錄表單登錄時,不需要has_perm函數,is_staff和is_superuser字段?