且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何判断用户的电子邮件地址是否已使用Django,allauth,rest-auth和自定义用户进行了验证

更新时间:2022-04-08 04:53:47

啊哈!感谢这篇文章,我想我有一个答案。

Aha! Thanks to this post and this post, I think I have an answer.

电子邮件地址的状态保存在单独的表EmailAdress中,而不是用户模型的一部分。可以在modelviewset中访问它,如下所示:

The email address's status is saved in a separate table EmailAdress, not as part of the User model. This can be accessed in a modelviewset as follows:

api.py

from allauth.account.admin import EmailAddress

class ListViewSet(viewsets.ModelViewSet):
    ...

    def get_queryset(self):
        # can view public lists and lists the user created
        if self.request.user.is_authenticated:
            print('is there a verified email address?')
            print(EmailAddress.objects.filter(user=self.request.user, verified=True).exists())

            ...

如果用户具有任何已验证的电子邮件地址,它将返回True。

This will return True if the user has any verified email address.

但是,将验证状态添加到用户。可以使用

However, it's much more useful to add the verification status to the user. This can be done with a signal as explained here.

views.py

from allauth.account.signals import email_confirmed
from django.dispatch import receiver

@receiver(email_confirmed)
def email_confirmed_(request, email_address, **kwargs):
    user = email_address.user
    user.email_verified = True

    user.save()

现在在api.py中可以像这样检查:

Now in api.py you can check like this:

print(self.request.user.email_verified)

如果您只有一个无法更改的电子邮件地址或已删除。如果您允许多个电子邮件地址,我想您需要进行更多检查并相应地更新用户状态。但是我只有一个用于登录的电子邮件地址,所以我认为可以。

This works if you have a single email address that can't be changed or deleted. If you allow multiple email addresses I guess you'd need to make more checks and update the user's status accordingly. But I have only a single email address which is used for login, so I think that's OK.

我认为将'email_verified'设置为电子邮件的一部分是更好的做法用户个人资料,但这是一个有效的演示。

I think it would be better practice to make 'email_verified' part of a user profile, but this is a working demo.