如何判断用户的电子邮件地址是否已使用Django,allauth,rest-auth和自定义用户进行了验证 [英] How to tell if user's email address has been verified using Django, allauth, rest-auth and a custom user

查看:109
本文介绍了如何判断用户的电子邮件地址是否已使用Django,allauth,rest-auth和自定义用户进行了验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Django 2.0.10与其他框架,rest-auth和allauth结合使用。我有一个自定义的用户模型。

I'm using Django 2.0.10 with rest-framework, rest-auth and allauth. I have a custom user model.

我已经使用allauth视图进行了电子邮件验证。用户注册时将发送验证电子邮件。如果我单击电子邮件中的链接,则会转到带有一个按钮的页面,单击该按钮可对电子邮件进行验证。所有这一切都没有错误。但是我不知道这实际上是什么。用户数据中的任何字段似乎都没有变化。

I've got email verification working by using the allauth view. The verification email is sent when a user registers. If I click the link in the email, I'm taken to a page with a button to click to verify the email. This all works without error. However what I can't find out is what this actually does. No field in the user's data seems to change.

我想要的行为是使用户能够注册和登录,但只能向其中添加内容他们确认电子邮件后才访问该网站。

The behaviour I want is for users to be able to register and login, but only to be able to add content to the site after they have verified their email.

编辑:此post 给出了部分答案,但没有说明如何将验证状态另存为用户的属性,以便您在加载用户数据时可以在前端对其进行检查。

this post gives part of the answer but doesn't say how to save the verification status as a property of the user so that you can check it in the front end when you load the user data.

settings.py

settings.py

# django rest auth
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
OLD_PASSWORD_FIELD_ENABLED = True
LOGOUT_ON_PASSWORD_CHANGE = False
ACCOUNT_EMAIL_VERIFICATION = 'optional'

api / urls.py

api/urls.py

from allauth.account.views import confirm_email

urlpatterns = [
    re_path(r'^rest-auth/registration/account-confirm-email/(?P<key>[-:\w]+)/$', confirm_email,
     name='account_confirm_email'),
...
]

users / models.py

users/models.py

import uuid 

from django.contrib.auth.models import AbstractUser, UserManager
from django.db import models
from django.utils.http import int_to_base36

class CustomUserManager(UserManager):
    def get_by_natural_key(self, username):
        case_insensitive_username_field = '{}__iexact'.format(self.model.USERNAME_FIELD)
        return self.get(**{case_insensitive_username_field: username})

ID_LENGTH = 12

def pkgen():
    from base64 import b32encode
    from hashlib import sha1
    from random import random

    pk = int_to_base36(uuid.uuid4().int)[:ID_LENGTH]
    return pk

class CustomUser(AbstractUser):
    objects = CustomUserManager()
    slug = models.CharField(max_length=ID_LENGTH, default=pkgen, editable=False)
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

    def __str__(self):
        return self.email

当用户登录时,如何查找他们是否已验证其电子邮件地址?谢谢您的帮助!

When a user logs in, how can I find out if they have verified their email address? Thanks for any help!

推荐答案

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

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.

这篇关于如何判断用户的电子邮件地址是否已使用Django,allauth,rest-auth和自定义用户进行了验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆