加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 设计如何更改reset_password_token错误

发布时间:2020-12-16 21:04:31 所属栏目:百科 来源:网络整理
导读:我试图完全覆盖Devise的错误消息’reset_password_token is invalid’.我想读它“密码重置链接已被使用”.我怎样才能做到这一点?在devise.en.yml中没有看到这个字段或关键字. 解决方法 重置密码令牌无效消息是更新密码时抛出的验证错误,并且不是特定于设备
我试图完全覆盖Devise的错误消息’reset_password_token is invalid’.我想读它“密码重置链接已被使用”.我怎样才能做到这一点?在devise.en.yml中没有看到这个字段或关键字.

解决方法

重置密码令牌无效消息是更新密码时抛出的验证错误,并且不是特定于设备的错误(其中的消息存储在 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 => [“无效”]}

devise_error_messages method重新格式化为“重置密码令牌无效”.

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

步骤如下:

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

更多关于Customizing Devise controllers

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读