【问题标题】:Unable to perform password complexity implementation in Ruby on Rails?无法在 Ruby on Rails 中执行密码复杂性实现?
【发布时间】:2016-04-18 17:31:25
【问题描述】:

我对此主题进行了很多研究,但由于某种原因,我无法在我的 Ruby on Rails Web 应用程序上执行密码复杂性实现。我已经安装了设计 gem 并关注了 Best flexible rails password security implementationHow to validate password strength with Devise in Ruby on Rails?

当我在线查看时,我的正则表达式似乎正在工作

/\A(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[[:^alnum:]])/x

但是一旦我在我的 user.rb 中实现它,它就不起作用了。

我的 user.rb 文件:

#Active Record for Users
class User < ActiveRecord::Base
  belongs_to :entity
  has_and_belongs_to_many :groups, :join_table => "users_groups"
  has_many :surveys, inverse_of: :user
  has_many :results, inverse_of: :user

  validates :password, :firstName, :email, :salt, :role, :timezone, presence: true
  validates :email, :uniqueness => {:scope => :entity_id}
  validates_format_of :email, :with => /.+@.+\..+/i

  devise :database_authenticatable, :validatable
  validate :password_complexity

  #User Authentication
  def self.authenticate(email="", lpassword="")
    users = User.where(email: email)
    results = []
    users.each do |user|
      if user && user.match_password(lpassword)
      results.push(user)
      end
    end
    if(results.length == 0)
    return false
    else
    return results
    end
  end

  #Password Check
  def match_password(lpassword="")
        return (BCrypt::Password.new(password).is_password?(lpassword+salt))
    end

  #Password Authentication
  def password_complexity
      if password.present? and not password.match(/\A(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[[:^alnum:]])/x)
        errors.add :password, "must include at least one lowercase letter, one uppercase letter, and one digit"
      end
   end

end

【问题讨论】:

  • “只是不起作用”是什么意思?请编辑您的问题,以包括您为测试此代码所采取的步骤、您期望的结果以及您得到的结果。
  • pry断点设置为#password_complexity方法并手动尝试匹配为:/\A(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[[:^alnum:]])/x =~ password
  • 这不起作用意味着如果我输入与正则表达式不匹配的错误密码,它仍然会接受它。
  • 所以,我能够解决这个问题。这是一个非常愚蠢的解决方案。输入的密码首先使用 BCrypt 进行哈希处理,然后进行验证。因此,它将始终通过几乎所有的测试(包括长度和特殊字符的匹配)。无论如何,下面的代码都能完美运行。

标签: ruby-on-rails ruby regex devise passwords


【解决方案1】:

你所做的应该有效,但为什么不简单地这样做

validates :password, format: { with: /\A(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[[:^alnum:]])/, message: "must include at least one lowercase letter, one uppercase letter, and one digit" }

【讨论】:

  • 我在函数中这样做的唯一原因是因为我想稍后将其分解,以便用户可以准确地知道他缺少什么,而不仅仅是一般消息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-16
  • 2016-12-05
  • 1970-01-01
相关资源
最近更新 更多