设计自定义密码验证导致控制台中的无效用户

Devise custom password validation leads invalid user in console

我正在尝试在我用于用户管理的项目中添加自定义密码验证。我成功创建用户,或手动更改用户密码。但是,如果我退出我的控制台并再次打开它,我的有效用户(在最后一步)将变为无效。

我正在使用 devise 4.6.2 和 rails 5.2.0

这是我的用户模型

class User < ApplicationRecord


  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  validates :password, 
            format: { with: /\A(?=.*\d)(?=.*[A-Z])(?=.*\W)[^ ]{7,}\z/,
                      message: 'Password should have more than 7 characters including 1 uppercase letter, 1 number, 1 special character'
                    }

end

当我在控制台中尝试时

u = User.new(email: 'test@test.com', password: 'Abc123!', password_confirmation: 'Abc123!')
u.valid? # TRUE
u.save

然后

u = User.last # return exact above user
u.valid? # FALSE
u.errors.full_messages # Password Password should have more than 7 characters including 1 uppercase letter, 1 number, 1 special character

我做错了什么吗?

User.last 没有密码。这就是引发错误的原因。

非常相似的问题: https://github.com/plataformatec/devise/wiki/How-To:-Set-up-simple-password-complexity-requirements

嗯,你可以在配置中设置密码长度 devise.rb。

config.password_length = 7..128

如果您想在 devise.rb 上设置密码格式,试试这个 gem https://github.com/phatworx/devise_security_extension

谢谢,我想出了一个使用自定义验证器的解决方案

class User < ApplicationRecord
  validate :password_regex

  private

  def password_regex
    return if password.blank? || password =~ /\A(?=.*\d)(?=.*[A-Z])(?=.*\W)[^ ]{7,}\z/

    errors.add :password, 'Password should have more than 7 characters including 1 uppercase letter, 1 number, 1 special character'
  end
end