20180202000002_custom_ldap_login_attribute.rb 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. class CustomLdapLoginAttribute < ActiveRecord::Migration[5.1]
  3. def up
  4. # return if it's a new setup
  5. return if !Setting.exists?(name: 'system_init_done')
  6. return if no_change_needed?
  7. perform_changes
  8. end
  9. private
  10. def perform_changes
  11. delete_spared
  12. update_config
  13. end
  14. def delete_spared
  15. # remove samaccountname which is always wrong if there is more than
  16. # one other login attribute since it's automatically added
  17. ldap_config[:user_attributes].delete('samaccountname')
  18. # this should not happen but remove any other duplicate that
  19. # maps to login and keep the "first" in the list
  20. # - which is more or less random
  21. login_attributes.reject { |e| e == 'samaccountname' }.drop(1).each do |spared|
  22. ldap_config[:user_attributes].delete(spared)
  23. end
  24. end
  25. def update_config
  26. Import::Ldap.config = ldap_config
  27. end
  28. def login_attributes
  29. @login_attributes ||= ldap_config[:user_attributes].select { |_local, remote| remote == 'login' }.keys
  30. end
  31. def no_change_needed?
  32. return true if ldap_config.blank?
  33. return true if ldap_config[:user_attributes].blank?
  34. ldap_config[:user_attributes].values.count('login') < 2
  35. end
  36. def ldap_config
  37. @ldap_config ||= Import::Ldap.config
  38. end
  39. end