繁体   English   中英

设计如何更改reset_password_token错误

[英]Devise how to change reset_password_token error

我试图完全覆盖Devise的错误消息'reset_password_token is invalid' 我想读它"password reset link has already been used." 我怎样才能做到这一点? devise.en.yml中没有看到这个字段或关键字。

Reset password token is invalid消息是更新密码时抛出的验证错误,并且不是特定于设备的错误(对于该消息存储在devise.en.yml中 )。

此验证发生在devise / passwords_controller#update方法中。 代码包括:

# PUT /resource/password
def update
  self.resource = resource_class.reset_password_by_token(resource_params)
  yield resource if block_given?

  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_flashing_format?
    sign_in(resource_name, resource)
    respond_with resource, location: after_resetting_password_path_for(resource)
  else
    respond_with resource
  end
end

self.resource = resource_class.reset_password_by_token(resource_params)行设置resource.errors对象,其中与reset_password_token相关的错误消息无效。

在此行之后检查resource.errors的值将显示以... @messages={:reset_password_token=>["is invalid"]}结尾的大哈希值... @messages={:reset_password_token=>["is invalid"]}

devise_error_messages方法将其重新格式化为“重置密码令牌无效”。

要更改此消息,应自定义密码控制器,并将update方法更改为具有不同的错误消息哈希。

步骤如下:

1)自定义密码控制器的路由

# config/routes.rb
devise_for :users, :controllers => { :passwords  => "passwords" }

2)创建自定义密码控制器

# app/controllers/passwords_controller.rb
class PasswordsController < Devise::PasswordsController

end

3)自定义更新方法以更改错误消息:

# app/controllers/passwords_controller.rb 
# Include the update method as it is fully, with the following changes in the else block:

def update
  ...

  if resource.errors.empty?
    ...
  else
    if resource.errors.messages[:reset_password_token]
      resource.errors.messages.delete(:reset_password_token)
      resource.errors.messages[:password_reset_link] = ["has already been used"]
    end
    respond_with resource
  end

有关自定义Devise控制器的更多信息

比覆盖passwords_controller更简单的解决方案就是修改视图:

在app / views / devise / passwords / edit.html.haml(或等效的erb)中,只需将此条件放在表单中:

 - if resource.errors[:reset_password_token].present?
  .alert.alert-danger
    This password reset URL has expired. You may have requested to reset your password more than once. Follow the link in the most recent email or 
    = link_to 'request to reset your password again.', new_user_password_path

你可能想要删除这两行:

= f.error_notification
= f.full_error :reset_password_token

暂无
暂无

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

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