【问题标题】:Expire the user activation link and remove from database in django使用户激活链接过期并从 django 中的数据库中删除
【发布时间】:2019-08-06 10:14:58
【问题描述】:

我有一个用户注册,在单击与发送到其电子邮件地址的令牌的链接后,用户的帐户被激活。如果在 24 小时内未点击特定链接,我想使链接失效并从数据库中删除他们的数据。

我在一处看过,链接在 48 小时后过期,对吗?

这是我的问题 -

如何自动删除那些在 24 小时内没有点击激活链接的用户?

(到目前为止,我可以通过转到管理面板并检查电子邮件是否确认来做到这一点)

这是我的激活函数,

def activate(request, uidb64, token):
    try:
       uid = force_text(urlsafe_base64_decode(uidb64))
       user = User.objects.get(pk=uid)
    except (TypeError, ValueError, OverflowError, ObjectDoesNotExist):
       user = None

    if user is not None and account_activation_token.check_token(user, token):
       user.is_active = True
       user.email_confirmed = True
       user.save()
       login(request, user)
       return redirect('home')
    else:
       return render(request, 'user/account_activation_invalid.html')

这是我创建令牌的tokens.py,

from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils import six

class AccountActivationTokenGenerator(PasswordResetTokenGenerator):
   def _make_hash_value(self, user, timestamp):
       return (
           six.text_type(user.pk) + 
           six.text_type(timestamp) + 
           six.text_type(user.email_confirmed)
           )

 account_activation_token = AccountActivationTokenGenerator()

我应该改变什么来实现这一点?

【问题讨论】:

  • 一种通用的方法是创建一个crontab,它执行一个django command 以删除任何符合filter(timestamp < now - 1 day) 标准的激活链接。

标签: python django django-views


【解决方案1】:

令牌的默认到期时间为 3 天(72 小时)。

您不需要将令牌保存在数据库中。令牌已经包含创建时间的时间戳。因此,您需要做的就是在您的自定义类中重写 check_token 方法并检查时间戳是否为 24 小时。

大部分代码都可以从原始方法中逐字复制。请参阅source code on github

你所要做的就是改变line 49

示例代码:

class AccountActivationTokenGenerator(...):
    ...
    def check_token(self, user, token):

        ...
        if (self._num_days(self._today()) - ts) > 1: # 1 day = 24 hours
            return False

        ...

更新:

要在 24 小时后删除未经验证的用户,您可以创建一个每 24 小时运行一次的 cron 作业,并检查数据库中是否存在未经验证的用户,如果超过 24 小时,则将其删除。

这是一个给出过程概要的答案:Django - Set Up A Scheduled Job?。要创建 cron 作业,请参阅操作系统的文档。

另一种添加 cron 作业的方法是使用 django 应用程序,例如 django-crondjango-crontab。它们是专门为简化此任务而创建的,但一般原则与链接答案中描述的相同。

【讨论】:

  • 这将在一天后到期。但这不会自动删除用户。有什么关于这方面的吗?
  • @BidhanMajhi 啊!你的问题标题让我感到困惑。我已经用更多信息更新了答案。
  • @xyres 是否可以检查不到一个小时的时间?喜欢if (self._num_days(self._today()) - ts) > 0.04: # 1 hour out of 24 is 0.042 return False
  • @m00ncake No. self._today()ts 都是 date 对象。减去它们将返回days 中的值作为整数。由于令牌中使用的时间戳(ts)只有日期信息,因此您需要覆盖令牌生成方法,并使用小时和分钟信息(即datetime对象)保存时间戳。
猜你喜欢
  • 2014-01-31
  • 1970-01-01
  • 2020-12-26
  • 1970-01-01
  • 2020-03-27
  • 1970-01-01
  • 2011-05-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多