Django CustomUser重新定义密码字段

时间:2017-06-23 15:31:07

标签: python django django-models

突然间,我需要使用我现有的一个模型进行身份验证。我知道有几种方法可以做到这一点,但在这里我想知道是否可以用我选择的方式重新定义密码字段?

更具体一点:我希望django知道我的access_key字段是用户密码字段。

但目前的代码预先假定我要在公司模型中添加另一个字段密码。

from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
from django.db import models

from django_extensions.db.fields.encrypted import EncryptedCharField


class CompanyManager(BaseUserManager):
    def create_user(self, name, email, access_key=None):
        if not email:
            raise ValueError('Company must have an email address')

        company = self.model(
            email=CompanyManager.normalize_email(email),
        )
        if access_key is not None:
            company.access_key = access_key

        company.save(using=self._db)

        return company

    def create_superuser(self, name, email, access_key):
        company = self.create_user(name, email, access_key)
        company.is_admin = True
        company.save()

        return company


class Company(AbstractBaseUser):
    name = models.CharField(max_length=64, blank=False, null=False,
                            unique=True)
    email = models.CharField(max_length=254, blank=False, null=False,
                             unique=True)
    access_key = EncryptedCharField(max_length=18)
    verification_key = EncryptedCharField(max_length=20, blank=True,
                                          null=True)
    is_confirmed = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)
    callback_url = models.URLField(blank=False, null=True)
    objects = CompanyManager()

    USERNAME_FIELD = 'name'
    REQUIRED_FIELDS = ['email']

0 个答案:

没有答案