繁体   English   中英

首次成功登录后重置密码

[英]Reset password after first successful login

我正在使用 Django 中现有的身份验证功能构建一个 Web 应用程序,其中管理员使用用户名和密码创建用户配置文件。 管理员创建的用户名和密码将提供给用户登录。 因此,出于安全原因,我需要在用户第一次成功登录后要求用户重置密码(由管理员提供)。 要重置密码,我将显示模板,用户应该只输入新密码和新密码以进行确认。 这个新密码将在 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)”也不会重定向。

请帮我

为什么不将 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM