3

正如我们在不同的网站上看到的,用户注册后,它会向用户的电子邮件发送一个 6/5 字符的激活码。用户应在网站上提交代码以激活他们的帐户。我正在尝试做同样的事情,但无法弄清楚如何使用 djoser 在 django-rest-framework 中做到这一点。

目前,我正在使用 Djoser 进行注册和激活。Djoser 在电子邮件中发送激活 URL;单击它会激活帐户并且它工作正常。

如何向用户发送 6 个字符的字母数字激活代码,而不是发送整个 URL?

我正在使用:django-rest-framework、django-rest-framework-jwt、djoser

4

3 回答 3

2

我在项目中使用了以下变体:

# models.py
import random

from django.conf import settings
from django.db import models


def generate_activation_code():
    return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(6))


class ActivationCode(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    code = models.CharField(max_length=6, default=generate_activation_code)


# views.py
from django.http import Http404

def register_user(request):
    # create your `new_user` however you see fit
    code = ActivationCode.objects.create(user=new_user)
    send_mail(
        'Activate Your Account',
        'Here is the activation code: %s' % code,
        'from@example.com',
        [user.email]
    )
    render(request, 'activation_sent.html')

def check_activation_code(request, code):
    try:
        ActivationCode.objects.get(code=code)
        # ... All set, activate & login the user, & delete the activation code
    except ActivationCode.DoesNotExist:
        raise Http404

    return render(request, 'welcome.html')

增强功能可能包括为您在视图中签入的内容添加到期日期ActivationCode,和/或清理旧代码的管理作业。

于 2019-07-25T16:29:44.200 回答
1

不要创建随机值,而是编码一些唯一的用户数据并将其附加到 url。像这样

import jwt
data = {'email' : "test@test.com"} # Some unique field for reference
secret_key = "test"
algorithm = "HS256" # You can use MD5 or whatever you want
jwt.encode(data, secret_key, algorithm)

在他们单击邮件激活 url 后,您可以解码并验证数据库中的唯一字段。为此,您不想将代码保存在数据库中。这是我的建议

于 2018-01-05T09:41:11.180 回答
0

您可以生成 6 位随机数:

import random  
codeval = random.randint(111111,999999)

并通过电子邮件发送。您可以保留完全相同的随机数副本。当用户将给出他的号码时。您可以将其与存储的匹配。如果匹配,则您将激活用户配置文件。

于 2018-01-05T04:00:01.527 回答