20180202000002_custom_ldap_login_attribute.rb 1.2 KB

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