django - Allauth - 如何禁用社交帐户的重置密码?

标签 django django-allauth

我希望社交用户只能在没有密码的情况下登录。因此,我想在/accounts/password/reset/处为社交用户禁用密码重置。

我知道我需要在 allauth.accounts.forms.py 的代码中添加条件

class ResetPasswordForm(forms.Form):

    email = forms.EmailField(
        label=_("E-mail"),
        required=True,
        widget=forms.TextInput(attrs={"type": "email", "size": "30"}))

    def clean_email(self):
        email = self.cleaned_data["email"]
        email = get_adapter().clean_email(email)
        self.users = filter_users_by_email(email)
        if not self.users.exists():
            raise forms.ValidationError(_("The e-mail address is not assigned"
                                          " to any user account"))
        return self.cleaned_data["email"]

我正在考虑这个解决方案,但我不知道如何正确执行:

  elif SocialAccount.objects.filter(provider='facebook'):
      raise forms.ValidationError(_("You are using a social account.")

最佳答案

Allauth 的可扩展性不是问题。 self.users 包含提供电子邮件的所有用户,但如果您设置了 ACCOUNT_UNIQUE_EMAIL=True 或只是没有更改它(因此它是 True默认),那么您可以只使用第一个用户。每个用户都包含与 socialaccount_set 相关的管理员。因此,我们只需按 provider 名称过滤该设置,如果有任何项目,则该用户具有相关的社交帐户。因此,您可以继承 allauth 形式并在那里进行额外的检查:

# forms.py
class MyResetPasswordForm(ResetPasswordForm):
    def clean_email(self):
        email = self.cleaned_data["email"]
        email = get_adapter().clean_email(email)
        self.users = filter_users_by_email(email)
        if not self.users.exists():
            raise forms.ValidationError(_("The e-mail address is not assigned"
                                          " to any user account"))
        # custom code start
        elif self.users.first().socialaccount_set.filter(provider='facebook').exists():
            raise forms.ValidationError(_("You are using a social account.")
        # custom code end
        return self.cleaned_data["email"]

然后覆盖 allauth 设置以在重置密码 View 中使用您的表单:

# your settings
ACCOUNT_FORMS = {
    'reset_password': 'your_app.forms.MyResetPasswordForm'
}

我尚未测试此代码,因此它可能包含拼写错误,因此请随时发布任何进一步的问题。

关于django - Allauth - 如何禁用社交帐户的重置密码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30153161/

相关文章:

Django-allauth 在更改密码时更改重定向 url

python - 密码字段以纯文本形式显示密码

django - 重定向到管理员登录

django - 如何将 msgid 复制到 gettext 中的 msgstr 以制作 django i18n/translation?

Django 查询集单元测试

Django 管理和列宽通过 list_display

Django allauth 社交登录 : automatically linking social site profiles using the registered email

python - 如何允许用户删除 django allauth 中的帐户?

django - django-allauth 发送电子邮件时电子邮件主题行中的 "[Site]"

python - Django URL 文件错误