我正在使用Django中现有的Auth功能构建Web应用程序,其中admin使用用户名和密码创建用户个人资料。管理员创建的用户名和密码将提供给用户登录。因此,出于安全原因,我需要在用户首次成功登录后要求用户重置密码(由admin提供)。要重置密码,我将显示模板,用户应在该模板中仅输入新密码,然后再次输入新密码进行确认。此新密码将在sqlite数据库中更新。
因此,只要管理员更改用户密码即可。我需要要求用户在首次成功登录后重设密码。
这是我完成的实现。
models.py::在这里,当创建新用户时,我将布尔标志profile.force_password_change设置为TRUE。但是,无论何时更改现有用户密码或创建新用户,profile.force_password_change都不会设置为TRUE。
middleware.py :每当force_password_change设置为TRUE时,我都会使用中间件重定向以更改密码视图。
I have written below code to set profile.force_password_change to TRUE whenever new user is created or user password is changed by admin.
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)
pass
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 = True
profile.save()
except User.DoesNotExist:
pass
signals.pre_save.connect(password_change_signal, sender=User, dispatch_uid='dau_gui_app.models')
signals.post_save.connect(create_user_profile_signal, sender=User, dispatch_uid='dau_gui_app.models')
class PasswordChangeMiddleware:
def process_request(self, request):
if request.user.is_authenticated() and re.match(r'^/status/?', request.path) and not re.match(
r'^/change_password/?', request.path):
profile = request.user.get_profile()
if not profile.force_password_change:
return HttpResponseRedirect(views.change_password_view)
# return HttpResponseRedirect('/admin/password_change/')
Settings.py : 1.我启用了AUTH_PROFILE_MODULE ='dau_gui_app.UserProfile' 2. MIDDLEWARE_CLASSES =( 'django_session_timeout.middleware.PasswordChangeMiddleware', )
我在这里面临的问题是,当新用户首次登录时,我无法设置标志“ profile.force_password_change = True”。当密码更改或首次成功登录后,“ return HttpResponseRedirect(views.change_password_view)”也不会重定向。
请帮助我
答案 0 :(得分:1)
为什么在更改密码后不将force_password_change的默认值设置为True,然后又更改为False?
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
force_password_change = models.BooleanField(default=True)
class PasswordChangeMiddleware:
if request.user.is_authenticated() and re.match(r'^/status/?', request.path) and not re.match(r'^/change_password/?', request.path):
profile = request.user.get_profile()
if profile.force_password_change:
profile.force_password_change = False
profile.save()
return HttpResponseRedirect(redirect_url) #pass redirect url instead of view function name
注意:记住要迁移!
如果您需要任何帮助,请确实参考我在GitHub上的一些项目。例如 https://github.com/manojbalaji1/En-kart