避免使用 Django 发送临时电子邮件

问题描述 投票:0回答:2

我想阻止临时电子邮件并确保用户只有在电子邮件真实的情况下才能注册(例如 Gmail、Outlook、Yahoo)。

表格.py

class SginupForm(UserCreationForm):
    class Meta:
        model = User
        fields =('username', 'first_name','last_name','email','password1','password2' )

views.py

@unauthenticated_user
def signup_form(request):
    if request.method == 'POST':
        form=SginupForm(request.POST)
        if form.is_valid():
            user=form.save()
            send_action_email(user,request)
            messages.add_message(request, messages.SUCCESS,
                                 'we have sent ur activation link')
            return redirect('core:login')
   
    else:
        form=SginupForm()
    return render(request,'user/sign-up.html',{'form':form})
django email temp
2个回答
0
投票

没有一种自动方法可以知道电子邮件是否是临时电子邮件。所以我只会使用白名单。只需确保您包含所有最受欢迎的电子邮件提供商(通过 Google 搜索即可)。

创建电子邮件列表。为了良好的实践,这应该作为您的 views.py 文件顶部的常量。

ALLOWED_EMAILS = ["gmail.com", "outlook.com", "yahoo.com"]

然后,当您的用户提交注册表单时,只需验证电子邮件 地址以其中任何一个结尾。

以下条件检查电子邮件是否不以任何白名单电子邮件结尾。用户提交表单后立即添加它。添加您自己的自定义消息和重定向逻辑。

email = form.cleaned_data.get("email")
if not any(email.endswith(e) for e in ALLOWED_EMAILS):
    # Add a failure message to the request.
    # Redirect back to the login page.

0
投票

实际上有一个很好的应用程序:

https://github.com/disposable-email-domains/disposable-email-domains

然后你就可以:

>>> from disposable_email_domains import blocklist
>>> 'bearsarefuzzy.com' in blocklist
True

例如,在 CourtListener.com 中,我们做了这样的事情:

from disposable_email_domains import blocklist
from django.contrib.auth.forms import UserCreationForm

class UserCreationFormExtended(UserCreationForm):
    """A bit of an unusual form because instead of creating it ourselves,
    we are overriding the one from Django. Thus, instead of declaring
    everything explicitly like we normally do, we just override the
    specific parts we want to, after calling the super class's __init__().
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    class Meta:
        model = User
        fields = (
            "username",
            "email",
            "first_name",
            "last_name",
        )

    def clean_email(self):
        email = self.cleaned_data.get("email")
        user_part, domain_part = email.rsplit("@", 1)
        if domain_part in blocklist: # <-- Is it a blocked email domain??
            raise forms.ValidationError(
                f"{domain_part} is a blocked email provider",
                code="bad_email_domain",
            )
        return email

    # Security check for bonus points :)
    def clean_first_name(self):
        first_name = self.cleaned_data.get("first_name")
        if re.search(r"""[!"#$%&()*+,./:;<=>?@[\]_{|}~]+""", first_name):
            raise forms.ValidationError(
                "First name must not contain any special characters."
            )
        return first_name
© www.soinside.com 2019 - 2024. All rights reserved.