Class: UnpwnedValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/unpwned_validator.rb

Overview

Validator class for passwords

Examples

Validates that attribute is not pwned, but only in production.

class User < ActiveRecord::Base
  validates :password, unpwned: true, if: -> { Rails.env.production? }
end

Validates that attribute meets min/max and is not pwned.

class User < ActiveRecord::Base
  validates :password, unpwned: { min: 12, max: 128 }
end

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/unpwned_validator.rb', line 19

def validate_each(record, attribute, value)
  unpwn = Unpwn.new(**options.slice(:min, :max, :request_options))

  if unpwn.min && value.length < unpwn.min
    record.errors.add attribute, "is too short"
  end

  if unpwn.max && value.length > unpwn.max
    record.errors.add attribute, "is too long"
  end

  if unpwn.pwned?(value)
    record.errors.add attribute, options.fetch(:message,
      "is in common password lists, please choose something more unique")
  end
end