重置密码 - 跳过验证

时间:2017-10-11 07:25:17

标签: ruby-on-rails ruby-on-rails-4 devise

我需要在密码重置操作期间跳过zipcode验证。我到目前为止所写的内容如下:

User.rb

attr_accessor :email_confirmation, :user_role, :unit_user_property,
            :skip_validation, :skip_zip_validation, :login

validates_format_of :zip,
                  with: /\A\d{5}-\d{4}|\A\d{5}\z/,
                  message: 'should be of the format 12345 or 12345-1234',
                  unless: :skip_zipcode_validation?

# Return true/false to validate zipcode
# Skips validation if this returns true
def skip_zipcode_validation?
  skip_validation.present? || skip_zip_validation.present?
end

application_controller.rb

before_action :configure_permitted_parameters, if: :devise_controller?

protected



  def configure_permitted_parameters
    added_attrs = [:phone, :email, :password, :password_confirmation, :remember_me, :skip_zip_validation]

    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(added_attrs) }
    devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(added_attrs) }
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(added_attrs) }
  end

应用程序/视图/设计/口令/ edit.html.erb

<%= f.hidden_field :skip_zip_validation, value: true %>

但我仍然在密码重置时收到邮政编码验证错误。 在调试时,属性skip_zip_validation显示为nil。看起来该属性未分配给用户

有关如何解决此问题的任何想法?

2 个答案:

答案 0 :(得分:0)

确保:skip_zip_validation作为允许参数传递。

class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?

  def configure_permitted_parameters
    update_attrs = [:password, :password_confirmation, :current_password:, :skip_zip_validation]
    devise_parameter_sanitizer.permit :account_update, keys: update_attrs
  end
end

答案 1 :(得分:0)

通过覆盖设计reset_password_by_token方法来管理以解决此问题。

def self.reset_password_by_token(attributes={})
  original_token       = attributes[:reset_password_token]
  reset_password_token = Devise.token_generator.digest(self, :reset_password_token, original_token)

  recoverable = find_or_initialize_with_error_by(:reset_password_token, reset_password_token)
  recoverable.skip_zip_validation = true
    if recoverable.persisted?
      if recoverable.reset_password_period_valid?
        recoverable.reset_password(attributes[:password], attributes[:password_confirmation])
      else
        recoverable.errors.add(:reset_password_token, :expired)
      end
    end

  recoverable.reset_password_token = original_token if 
  recoverable.reset_password_token.present?
  recoverable
end