Mar*_*__C 2 authentication django
我有一个扩展 AbstractBaseUser 的 User 模型
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))
Run Code Online (Sandbox Code Playgroud)
在我的所有视图中,我使用 LoginRequiredMixin 进行身份验证,例如
class IndexView(LoginRequiredMixin, generic.TemplateView):
Run Code Online (Sandbox Code Playgroud)
我想不仅通过电子邮件和密码对用户进行身份验证,而且还想通过检查帐户是否已到期。
我的问题是 - 实现这一目标的最佳(最简单?)方法是什么。我是否按照此处所述编写自己的自定义身份验证后端?或者我应该写一个自定义的 Mixin 或中间件?
所以最后我的解决方案是创建我自己的自定义中间件。
我发现如何创建自定义 Django 中间件是一个有用的起点,但它对我不起作用,因为我使用的是 Django 2.0.1。官方文档解释了如何更新解决方案,我也发现这个 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
Run Code Online (Sandbox Code Playgroud)
(请注意, account_expiry 实际上是相关表(学校)中的一个字段,而不是根据我上面的原始问题在用户模型中)。
我更新了设置 MIDDLEWARE= 以包括
'common.middleware.AccountExpiry',
Run Code Online (Sandbox Code Playgroud)
它可以按照我的意愿工作。
归档时间: |
|
查看次数: |
1446 次 |
最近记录: |