password_policy.rb 809 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. # Check if password matches system settings
  3. class PasswordPolicy
  4. include ::Mixin::HasBackends
  5. class PasswordPolicy::Error < StandardError; end
  6. attr_reader :password
  7. # @param password [String, nil] to evaluate. nil is treated as empty string
  8. def initialize(password)
  9. @password = password || ''
  10. end
  11. def valid!
  12. return if valid?
  13. raise PasswordPolicy::Error, error.first
  14. end
  15. def valid?
  16. errors.blank?
  17. end
  18. def error
  19. errors.first
  20. end
  21. def errors
  22. @errors ||= applicable_backends
  23. .map { |backend| backend.new(password) }
  24. .reject(&:valid?)
  25. .map(&:error)
  26. end
  27. private
  28. def applicable_backends
  29. @applicable_backends ||= backends.select(&:applicable?)
  30. end
  31. end