【问题标题】:Password Issue when trying to update User Model尝试更新用户模型时出现密码问题
【发布时间】:2021-07-05 16:18:03
【问题描述】:

我正在尝试为我的应用程序实现忘记/恢复密码电子邮件,但在保存令牌时遇到问题。我使用 has_secure_password 和 password_digest 来保证安全。

这是我的控制器

  def create
    user = User.find_by_email(params[:email])
    user.send_password_reset if user
    flash[:notice] = 'E-mail sent with password reset instructions.'
    redirect_to new_session_path
  end

这是在用户模型中

def send_password_reset
        generate_token(:password_reset_token)
        self.password_reset_sent_at = Time.zone.now
        save!
        UserMailer.forgot_password(self).deliver# 
      end
     
      def generate_token(column)
        begin
          self[column] = SecureRandom.urlsafe_base64
        end while User.exists?(column => self[column])
      end

这是我遇到的错误

ActiveRecord::RecordInvalid - Validation failed: Password can't be blank, Password is too short (minimum is 6 characters):
  app/models/user.rb:11:in `send_password_reset'
  app/controllers/password_resets_controller.rb:8:in `create'

我只是对如何在没有密码的情况下验证用户感到困惑,以便我能够更新他们的内部字段(recoverytoken)。

【问题讨论】:

    标签: ruby-on-rails bcrypt


    【解决方案1】:

    这就是我在使用has_secure_password 时的做法。这里的关键是unless 部分。

    validates :password, presence: true, on: :update, length: { minimum: 5 }, 
      unless: proc { |x| x.password.blank? }
    

    【讨论】:

      猜你喜欢
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 2014-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      相关资源
      最近更新 更多