password_policy.rb 930 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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
  6. attr_reader :metadata
  7. def initialize(metadata)
  8. @metadata = metadata
  9. super(metadata.try(:first))
  10. end
  11. end
  12. attr_reader :password
  13. # @param password [String, nil] to evaluate. nil is treated as empty string
  14. def initialize(password)
  15. @password = password || ''
  16. end
  17. def valid!
  18. return if valid?
  19. raise PasswordPolicy::Error, error
  20. end
  21. def valid?
  22. errors.blank?
  23. end
  24. def error
  25. errors.first
  26. end
  27. def errors
  28. @errors ||= applicable_backends
  29. .map { |backend| backend.new(password) }
  30. .reject(&:valid?)
  31. .map(&:error)
  32. end
  33. private
  34. def applicable_backends
  35. @applicable_backends ||= backends.select(&:applicable?)
  36. end
  37. end