user_factory.rb 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. module Import
  2. class Ldap
  3. module UserFactory
  4. extend Import::StatisticalFactory
  5. def self.import(config: nil, ldap: nil, **kargs)
  6. # config might be an empty Hash due to the ImportJob payload
  7. # store column which will be an empty hash if the content is NULL
  8. if config.blank?
  9. config = Setting.get('ldap_config')
  10. end
  11. ldap ||= ::Ldap.new(config)
  12. @config = config
  13. @ldap = ldap
  14. user_roles = user_roles(ldap: @ldap, config: config)
  15. signup_role_ids = Role.signup_role_ids.sort
  16. @dry_run = kargs[:dry_run]
  17. pre_import_hook([], config, user_roles, signup_role_ids, kargs)
  18. import_job = kargs[:import_job]
  19. import_job_count = 0
  20. @ldap.search(config[:user_filter]) do |entry|
  21. backend_instance = create_instance(entry, config, user_roles, signup_role_ids, kargs)
  22. post_import_hook(entry, backend_instance, config, user_roles, signup_role_ids, kargs)
  23. next if import_job.blank?
  24. import_job_count += 1
  25. next if import_job_count < 100
  26. import_job.result = @statistics
  27. import_job.save
  28. import_job_count = 0
  29. end
  30. end
  31. def self.pre_import_hook(_records, *_args)
  32. super
  33. #cache_key = "#{@ldap.host}::#{@ldap.port}::#{@ldap.ssl}::#{@ldap.base_dn}"
  34. #if !@dry_run
  35. # sum = Cache.get(cache_key)
  36. #end
  37. sum ||= @ldap.count(@config[:user_filter])
  38. @statistics[:sum] = sum
  39. return if !@dry_run
  40. #Cache.write(cache_key, sum, { expires_in: 1.hour })
  41. end
  42. def self.add_to_statistics(backend_instance)
  43. super
  44. # no need to count if no resource was created
  45. resource = backend_instance.resource
  46. return if resource.blank?
  47. action = backend_instance.action
  48. known_actions = {
  49. created: 0,
  50. updated: 0,
  51. unchanged: 0,
  52. failed: 0,
  53. }
  54. if !@statistics[:role_ids]
  55. @statistics[:role_ids] = {}
  56. end
  57. resource.role_ids.each do |role_id|
  58. next if !known_actions.key?(action)
  59. @statistics[:role_ids][role_id] ||= known_actions.dup
  60. # exit early if we have an unloggable action
  61. break if @statistics[:role_ids][role_id][action].nil?
  62. @statistics[:role_ids][role_id][action] += 1
  63. end
  64. action
  65. end
  66. def self.user_roles(ldap:, config:)
  67. group_config = {
  68. filter: config[:group_filter]
  69. }
  70. ldap_group = ::Ldap::Group.new(group_config, ldap: ldap)
  71. ldap_group.user_roles(config[:group_role_map])
  72. end
  73. end
  74. end
  75. end