【问题标题】:Handling Django user subscription expiry date处理 Django 用户订阅到期日期
【发布时间】:2018-07-05 10:01:05
【问题描述】:

我有一个扩展 AbstractBaseUser 的用户模型

class User(AbstractBaseUser):
    email = models.EmailField(max_length=255, unique=True, default='abc123@gmail.com')
    forename = models.CharField(max_length=20, default='')
    surname = models.CharField(max_length=20, default='')
    account_expiry = models.DateField(default=datetime.now() + timedelta(days=365))

在我的所有视图中,我都使用 LoginRequiredMixin 进行身份验证,例如

class IndexView(LoginRequiredMixin, generic.TemplateView):

我不仅想通过电子邮件和密码验证用户身份,还想通过检查帐户是否到期。

我的问题是 - 实现这一目标的最佳(最简单?)方法是什么。我是否编写自己的自定义身份验证后端as described here?还是我应该编写自定义的 Mixin 或中间件?

【问题讨论】:

    标签: django authentication


    【解决方案1】:

    所以最终我的解决方案是创建自己的自定义中间件。

    我发现How to Create a Custom Django Middleware 是一个有用的起点,但它对我不起作用,因为我使用的是 Django 2.0.1。 The official docs 解释了如何更新解决方案,我还发现 this SO 的帖子很有用。

    所以我的代码看起来像:

    class AccountExpiry:
    
    def __init__(self, get_response):
        self.get_response = get_response
    
    def __call__(self, request):
        current_user = request.user
        response = self.get_response(request)
        expiry_path = reverse('accounts:account-expired')
    
        if current_user.is_anonymous is False:
            if current_user.admin is False and current_user.staff is False:
                if request.path not in [expiry_path]:
                    expiry_date = current_user.school.account_expiry
                    todays_date = datetime.today().date()
    
                    if todays_date > expiry_date:
                        return HttpResponseRedirect(expiry_path)
        return response
    

    (请注意,根据我上面的原始问题,account_expiry 实际上是相关表(学校)中的字段,而不是用户模型中的字段)。

    我更新了设置 MIDDLEWARE= 以包含

    'common.middleware.AccountExpiry',
    

    它可以按我的意愿工作。

    【讨论】:

    • 如果用户更改系统时间怎么办?
    【解决方案2】:

    您可以重新实现AbstractBaseUseris_authenticated 属性以在帐户过期时返回False

    为防止过期用户登录,您还可以覆盖check_password 以在帐户过期时返回 False。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-02
      • 2012-01-06
      • 1970-01-01
      • 2017-11-30
      • 2012-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多