Django中设置social-auth-app-django谷歌OAuth2创建用户的is_active为True
实现方案
你可以通过新增自定义的social-auth pipeline 步骤实现仅谷歌认证用户的自动激活,不会影响普通邮箱注册的用户流程,也避免了无密码用户默认激活的安全问题。
步骤1:编写自定义pipeline函数
在你的Django应用目录下新建pipeline.py文件,添加如下代码:
def activate_google_social_user(user, is_new, backend, *args, **kwargs): # 仅对谷歌OAuth2认证创建的新用户自动激活 if is_new and backend.name == 'google-oauth2': user.is_active = True # 仅更新is_active字段,提升性能也避免误改其他字段 user.save(update_fields=['is_active'])
步骤2:修改配置中的pipeline列表
修改settings.py里的SOCIAL_AUTH_PIPELINE配置,将上面的自定义函数添加到create_user步骤之后:
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', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', # 新增自定义激活步骤,替换yourapp为你的应用实际名称 'yourapp.pipeline.activate_google_social_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', )
额外说明
- 你之前在
UserManager里注释的无密码激活代码可以直接删除,避免后续逻辑冲突 - 该方案只会对走谷歌OAuth2认证流程创建的新用户生效,普通邮箱注册的用户依然保持默认
is_active=False,需要走邮件激活流程,完全符合你的需求
内容的提问来源于stack exchange,提问作者Anon
相关产品推荐
相关产品推荐

