我其实正在这样做的过程中.您需要三个组件:用户配置文件(如果您的站点上尚未使用),中间件组件和pre_save信号.
我的代码是在一个名为“帐户”的应用程序.
# myproject/accounts/models.py
from django.db import models
from django.db.models import signals
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
force_password_change = models.BooleanField(default=False)
def create_user_profile_signal(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
def password_change_signal(sender, instance, **kwargs):
try:
user = User.objects.get(username=instance.username)
if not user.password == instance.password:
profile = user.get_profile()
profile.force_password_change = False
profile.save()
except User.DoesNotExist:
pass
signals.pre_save.connect(password_change_signal, sender=User, dispatch_uid='accounts.models')
signals.post_save.connect(create_user_profile_signal, sender=User, dispatch_uid='accounts.models')
首先,我们创建一个带有外键的UserProfile给User.如果要强制他们更改密码,force_password_change boolean将正如其名称所述一样设置为true.你可以在这里做任何事情.在我的组织中,我们还选择每90天实施强制性更改,因此我还有一个DateTimeField,用于存储用户上次更改密码的时间.然后,在pre_save信号中设置password_changed_signal.
其次,我们有create_user_profile_signal.这主要是为了完整性而添加.如果您刚刚将用户配置文件添加到项目中,则需要一个post_save信号,每次创建一个UserProfile时都会创建一个UserProfile.这完成了这项任务.
第三,我们有password_changed_signal.这是一个pre_save信号,因为在该过程的这一点上,用户表中的实际行没有被更新.因此,我们可以访问以前的密码和要保存的新密码.如果两者不匹配,那意味着用户已经更改了密码,然后我们可以重新设置force_password_change布尔值.这将是重点,您也可以在此处处理您添加的任何其他内容,例如设置前面提到的DateTimeField.
最后两行将两个功能附加到其适当的信号.
如果还没有,您还需要将以下行添加到项目的settings.py(更改应用程序标签和型号名称以匹配您的设置):
AUTH_PROFILE_MODULE = 'accounts.UserProfile'
涵盖了基础知识.现在我们需要一个中间件组件来检查我们的force_password_change标志的状态(以及任何其他必要的检查).
# myproject/accounts/middleware.py
from django.http import HttpResponseRedirect
import re
class PasswordChangeMiddleware:
def process_request(self, request):
if request.user.is_authenticated() and \
re.match(r'^/admin/?', request.path) and \
not re.match(r'^/admin/password_change/?', request.path):
profile = request.user.get_profile()
if profile.force_password_change:
return HttpResponseRedirect('/admin/password_change/')
这个非常简单的中间件挂钩进入页面加载过程的process_request阶段.它检查1)用户已经登录,2)他们正在尝试访问管理员中的一些页面,3)他们正在访问的页面不是密码更改页面本身(否则,你会得到一个无限循环的重定向).如果所有这些都为真,并且force_password_change标志已设置为True,则将用户重定向到密码更改页面.在他们更改密码(触发前面讨论的pre_save信号)之前,他们将无法在别的地方导航.
最后,您只需要将这个中间件添加到项目的settings.py(再次根据需要更改导入路径):
MIDDLEWARE_CLASSES = (
# Other middleware here
'myproject.accounts.middleware.PasswordChangeMiddleware',
)
python配置文件密码管理_python – 可以在django管理员中实现“下次登录时更改密码”类型功能吗?...