使用自定义用户模型和 UserManager 使用 python-social-auth 创建 django 用户时出现问题

Issue creating a django user with python-social-auth with a custom User model and UserManager

这似乎不是一个独特的问题,但我在解决方案中遗漏了一些东西。我正在使用 python-social-auth 并使用 Google 登录。一切似乎都很顺利,直到它到达管道的 create_user 部分。我有一个自定义用户模型和 UserManager。在我的用户模型上,我确实有一个 role 属性 连接到一些 choices。当社交身份验证启动并让某人登录时,它会在我的用户管理器中调用 create_user,但它只传递电子邮件,没有其他字段。我试图连接到管道并通过将所需的 role 属性 添加到 details 社会身份验证字典来添加它,但这似乎没有任何效果。我应该如何连接到创建用户 属性 以添加就社交身份验证而言不存在的字段?

用户模型

class User(AbstractBaseUser, PermissionsMixin):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=timezone.now)
    email = models.EmailField(_("email address"), unique=True)
    first_name = models.CharField(max_length=240, blank=True)
    last_name = models.CharField(max_length=240, blank=True)
    role = models.IntegerField(choices=RoleChoices.choices)

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = []

    objects = UserManager()

    def __str__(self):
        return self.email

    @property
    def full_name(self):
        return f"{self.first_name} {self.last_name}".strip()

还有我的用户管理器:

class UserManager(BaseUserManager):
    """
    Custom user model manager where email is the unique identifiers
    for authentication instead of usernames.
    """

    def create_user(self, email, password, **extra_fields):
        """
        Create and save a User with the given email and password.
        """
        if not email:
            raise ValueError(_("The Email must be set"))

        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)

        if password is not None:
            user.set_password(password)

        user.save()
        return user

    def create_superuser(self, email, password=None, **extra_fields):
        """
        Create and save a SuperUser with the given email and password.
        """
        extra_fields.setdefault("is_staff", True)
        extra_fields.setdefault("is_superuser", True)
        extra_fields.setdefault("is_active", True)
        extra_fields.setdefault("role", 1)

        if extra_fields.get("is_staff") is not True:
            raise ValueError(_("Superuser must have is_staff=True."))
        if extra_fields.get("is_superuser") is not True:
            raise ValueError(_("Superuser must have is_superuser=True."))
        return self.create_user(email, password, **extra_fields)

社交身份验证配置:

# Social Auth Config
AUTHENTICATION_BACKENDS = (
    'social_core.backends.google.GoogleOAuth2',
    'django.contrib.auth.backends.ModelBackend',
)

LOGIN_URL = 'login'
LOGOUT_URL = 'logout'
LOGIN_REDIRECT_URL = 'admin'
SOCIAL_AUTH_POSTGRES_JSONFIELD = True
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.getenv('GOOGLE_CLIENT_ID')
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.getenv('GOOGLE_CLIENT_SECRET')
SOCIAL_AUTH_USER_MODEL = 'search.User'
SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL = True
SOCIAL_AUTH_GOOGLE_OAUTH2_IGNORE_DEFAULT_SCOPE = True
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [
    'https://www.googleapis.com/auth/calendar',
    'https://www.googleapis.com/auth/calendar.readonly',
    'https://www.googleapis.com/auth/userinfo.profile',
    'profile',
    'email'
]

SOCIAL_AUTH_PIPELINE = (
    'social_core.pipeline.social_auth.social_details',
    'social_core.pipeline.social_auth.social_uid',
    'social_core.pipeline.social_auth.auth_allowed',
    'social_core.pipeline.social_auth.social_user',
    'social_core.pipeline.user.get_username',
    'search.socialauth.add_role',
    'social_core.pipeline.user.create_user',
    'social_core.pipeline.social_auth.associate_user',
    'social_core.pipeline.social_auth.load_extra_data',
    'social_core.pipeline.user.user_details',
)

最后是 add_role 函数:

from .choices import RoleChoices


def add_role(**kwargs):
    kwargs['details']['role'] = RoleChoices.ARTIST
    return kwargs

这不起作用的原因是 create_user 函数显式过滤 details 的内容以仅包含键 specified in a USER_FIELDS setting。这默认为

USER_FIELDS = ['username', 'email']

所以其他任何内容都将被忽略。它似乎没有记录在案,但您应该能够通过如下创建设置来覆盖它:

SOCIAL_AUTH_USER_FIELDS = ['username', 'email', 'role']

这将确保您的 role 传递给用户实例。

您的管道和配置的其余部分看起来不错。