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

本文介绍如何在Rails应用中使用Sorcery会员系统进行密码验证,并实现旧密码确认功能。通过自定义验证和虚拟属性,确保用户更改密码时必须输入正确的旧密码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用了会员系统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 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值