密码更改后设计验证登录

Posted

技术标签:

【中文标题】密码更改后设计验证登录【英文标题】:Devise authentication logs in after password change 【发布时间】:2012-05-26 08:20:27 【问题描述】:

在 Rails 中设计身份验证 gem。

如何防止“忘记密码”链接更改密码后自动登录?

理想情况下,最好显示带有“新密码已保存”消息的页面。

【问题讨论】:

【参考方案1】:

截至 Devise 3.5.0,此行为可以通过设置来控制,可以在 config/initializers/devise.rb 中找到:

# When set to false, does not sign a user in automatically after their password is
# reset. Defaults to true, so a user is signed in automatically after a reset.
config.sign_in_after_reset_password = false

显示的闪烁消息将是Your password has been changed successfully.,但可以在config/locales/devise.en.yml 中调整:

en:
  devise:
    passwords:
      updated_not_active: New password has been saved

【讨论】:

如果我使用自定义的用户控制器怎么办?我在devise.rb 中改变了这种行为,但没有任何改变,sign_in current_user, bypass:true 也不起作用。 取决于您的控制器的外观。它是否继承自某个设计控制器?你打电话给super?如果没有,您必须自己实现逻辑。看看passwords controller,这里使用了设置。【参考方案2】:

这是基于 3.1.1 设计的更新

class Users::PasswordsController < Devise::PasswordsController

 def new
   super
 end

 def edit
   super
 end

 def create
   super
 end

 #override this so user isn't signed in after resetting password
 def update
    self.resource = resource_class.reset_password_by_token(resource_params)

    if resource.errors.empty?
      resource.unlock_access! if unlockable?(resource)
      flash_message = resource.active_for_authentication? ? :updated : :updated_not_active
      set_flash_message(:notice, flash_message) if is_navigational_format?

      respond_with resource, :location => after_resetting_password_path_for(resource)
    else
      respond_with resource
    end

  end

protected

   def after_resetting_password_path_for(resource)
     new_session_path(resource)
   end

结束

【讨论】:

【参考方案3】:

上述答案是正确的,但问题是它根据设计版本而有所不同。我按照上面所说的,我无法让它工作,一段时间后我发现我使用的设计版本不支持 resource_params 方法,然后我尝试了不同的版本并让它工作。

【讨论】:

【参考方案4】:

您需要覆盖 Devise 的 passwords_controller,您可以看到 here 的默认方法。首先,创建您自己的控制器,该控制器将从 Devise 控制器继承:

class User::PasswordsController &lt; Devise::PasswordsController

一旦你准备好你的控制器,添加你不想覆盖的所有其他方法,并简单地在它们内部调用 super。这将是 neweditcreate 方法。另外不要忘记添加受保护的after_sending_reset_password_instructions_path_for(resource_name) 方法。

您关心的覆盖方法是update 操作。

def update
  self.resource = resource_class.reset_password_by_token(resource_params)

  if resource.errors.empty?
    flash_message = resource.active_for_authentication? ? :updated : :updated_not_active
    set_flash_message(:notice, "Your flash message here")
    redirect_to new_user_session_path
  else
    respond_with resource
  end
end

我们在这里所做的更改是删除用于登录用户并重定向到登录页面的行,然后设置我们的自定义 Flash 消息。

最后,你必须告诉 devise 使用你的新控制器,所以在 routes.rb 中将 devise_for :users 更改为:

devise_for :users, :controllers =>  :passwords => 'users/passwords' 

应该这样做。

【讨论】:

以上是关于密码更改后设计验证登录的主要内容,如果未能解决你的问题,请参考以下文章

登陆界面代码

系统登录模块用例的设计原理?

登录界面测试用例设计

设置更改mysqlroot密码,连接mysql,mysql常用命令

通过 REST API 验证/更改密码

更改密码后 Heroku CLI 中的身份验证失败