File: devise_dynamic_password_length_validation.rb

package info (click to toggle)
gitlab 17.6.5-19
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 629,368 kB
  • sloc: ruby: 1,915,304; javascript: 557,307; sql: 60,639; xml: 6,509; sh: 4,567; makefile: 1,239; python: 406
file content (39 lines) | stat: -rw-r--r-- 1,600 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# frozen_string_literal: true

# Discard the default Devise length validation from the `User` model.

# This needs to be discarded because the length validation provided by Devise does not
# support dynamically checking for min and max lengths.

# A new length validation has been added to the User model instead, to keep supporting
# dynamic password length validations, like:

# validates :password, length: { maximum: proc { password_length.max }, minimum: proc { password_length.min } }, allow_blank: true

def length_validator_supports_dynamic_length_checks?(validator)
  validator.options[:minimum].is_a?(Proc) &&
    validator.options[:maximum].is_a?(Proc)
end

# Get the in-built Devise validator on password length.
password_length_validator = User.validators_on(:password).find do |validator|
  validator.kind == :length
end

# This initializer can be removed as soon as https://github.com/plataformatec/devise/pull/5166
# is merged into Devise.

# TODO: Update Devise. Issue: https://gitlab.com/gitlab-org/gitlab/issues/118450
if length_validator_supports_dynamic_length_checks?(password_length_validator)
  raise "Devise now supports dynamic length checks, please remove the monkey patch in #{__FILE__}"
else
  # discard the in-built length validator by always returning true
  def password_length_validator.validate(*_)
    true
  end

  # add a custom password length validator with support for dynamic length validation.
  User.class_eval do
    validates :password, length: { maximum: proc { password_length.max }, minimum: proc { password_length.min } }, allow_blank: true
  end
end