ruby on rails 自定义验证实现新旧密码对比

使用了会员系统sorcery https://github.com/Sorcery/sorcery

sorcery提供了密码对比

@user.valid_password?('secret')

ApplicationRecord user

密码验证rails提供了_confirmation,用于验证2个输入是否相同,可以直接使用

但是如果需要验证旧密码是否正确,就需要另外实现了,当然也可以在controller中实现,这里在model中实现

旧密码我取名old_password,当然数据库是没有这个字段的,所以需要虚拟一个出来

attr_accessor :old_password

接下来就是自定义验证

validate :old_password_confirmation, if: -> {changes[:crypted_password]}

def old_password_confirmation 
    if !self.valid_password?(old_password)
      errors.add(:old_password, "旧密码错误")
    end
  end 

完整代码

authenticates_with_sorcery!


  attr_accessor :old_password

  validates :name, presence: true
  validates :phone, presence: true, uniqueness: true
  validates :password, length: { minimum: 3 }, confirmation: true,
                       if: -> { new_record? || changes[:crypted_password] }
  validates :password_confirmation, presence: true,
                                    if: -> { new_record? || changes[:crypted_password] }

  validate :old_password_confirmation, if: -> {changes[:crypted_password]}


  def old_password_confirmation 
    if !self.valid_password?(old_password)
      errors.add(:old_password, "旧密码错误")
    end
  end 

猜你喜欢

转载自blog.csdn.net/tang05709/article/details/88050303