问题使用带有自定义用户模型和UserManager的python-social-auth创建django用户

问题描述 投票:1回答:1

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

用户模型

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()

和我的UserManager:

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

python django python-3.x python-social-auth
1个回答
0
投票

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

USER_FIELDS

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

USER_FIELDS = ['username', 'email']

然后将确保您的SOCIAL_AUTH_USER_FIELDS = ['username', 'email', 'role'] 被传递到用户实例。

您的其余管道和配置都很好。

© www.soinside.com 2019 - 2024. All rights reserved.