Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

Readd the two removed rake tasks as services

Oliver Güntherc991d6771cb6
diff --git a/app/models/ldap_auth_source.rb b/app/models/ldap_auth_source.rb
index 545e0d23a5a..112cd1f2719 100644
--- a/app/models/ldap_auth_source.rb
+++ b/app/models/ldap_auth_source.rb
@@ -119,6 +119,13 @@ class LdapAuthSource < AuthSource
parsed_filter_string || object_filter
end
+ ##
+ # Returns the filter object to search for a login
+ # adding the optional default filter
+ def login_filter(login)
+ Net::LDAP::Filter.eq(attr_login, login) & default_filter
+ end
+
def parsed_filter_string
Net::LDAP::Filter.from_rfc2254(filter_string) if filter_string.present?
end
@@ -162,15 +169,15 @@ class LdapAuthSource < AuthSource
# Get the user's dn and any attributes for them, given their login
def get_user_dn(login)
ldap_con = initialize_ldap_con(account, account_password)
- login_filter = Net::LDAP::Filter.eq(attr_login, login)
attrs = {}
+ filter = login_filter(login)
Rails.logger.debug do
- "LDAP initializing search (BASE=#{base_dn}), (FILTER=#{default_filter & login_filter})"
+ "LDAP initializing search (BASE=#{base_dn}), (FILTER=#{filter})"
end
ldap_con.search(base: base_dn,
- filter: default_filter & login_filter,
+ filter: filter,
attributes: search_attributes) do |entry|
attrs = if onthefly_register?
get_user_attributes_from_ldap_entry(entry)
diff --git a/app/services/ldap/base_service.rb b/app/services/ldap/base_service.rb
new file mode 100644
index 00000000000..8be57256190
--- /dev/null
+++ b/app/services/ldap/base_service.rb
@@ -0,0 +1,103 @@
+module Ldap
+ class BaseService
+ attr_reader :ldap
+
+ def initialize(ldap)
+ @ldap = ldap
+ end
+
+ def call
+ User.system.run_given do
+ OpenProject::Mutex.with_advisory_lock_transaction(ldap, 'import_users') do
+ perform
+ end
+ end
+ end
+
+ def perform
+ raise NotImplementedError
+ end
+
+ # rubocop:disable Metrics/AbcSize
+ def synchronize_user(user, ldap_con)
+ Rails.logger.debug { "[LDAP user sync] Synchronizing user #{user.login}." }
+
+ update_attributes = user_attributes(user.login, ldap_con)
+ if update_attributes.nil? && user.persisted?
+ Rails.logger.info { "Could not find user #{user.login} in #{ldap.name}. Locking the user." }
+ user.update_column(:status, Principal.statuses[:locked])
+ end
+ return unless update_attributes
+
+ if user.new_record?
+ try_to_create(update_attributes)
+ else
+ try_to_update(user, update_attributes)
+ end
+ end
+ # rubocop:enable Metrics/AbcSize
+
+ # Try to create the user from attributes
+ def try_to_update(user, attrs)
+ call = Users::UpdateService
+ .new(model: user, user: User.system)
+ .call(attrs)
+
+ if call.success?
+ # Ensure the user is activated
+ call.result.update_column(:status, Principal.statuses[:active])
+ Rails.logger.info { "[LDAP user sync] User '#{call.result.login}' updated." }
+ else
+ Rails.logger.error { "[LDAP user sync] User '#{user.login}' could not be updated: #{call.message}" }
+ end
+ end
+
+ def try_to_create(attrs)
+ call = Users::CreateService
+ .new(user: User.system)
+ .call(attrs)
+
+ if call.success?
+ Rails.logger.info { "[LDAP user sync] User '#{call.result.login}' created." }
+ else
+ Rails.logger.error { "[LDAP user sync] User '#{attrs[:login]}' could not be created: #{call.message}" }
+ end
+ end
+
+ ##
+ # Get the user attributes of a single matching LDAP entry.
+ #
+ # If the login matches multiple entries, return nil and issue a warning.
+ # If the login does not match, returns nil
+ def user_attributes(login, ldap_con)
+ # Return the first matching user
+ entries = find_entries_by(login: login, ldap_con: ldap_con)
+
+ if entries.count == 0
+ Rails.logger.info { "[LDAP user sync] Did not find LDAP entry for #{login}" }
+ return
+ end
+
+ if entries.count > 1
+ Rails.logger.warn { "[LDAP user sync] Found multiple entries for #{login}: #{entries.map(&:dn)}. Skipping" }
+ return
+ end
+
+ entries.first
+ end
+
+ def find_entries_by(login:, ldap_con: new_ldap_connection)
+ ldap_con
+ .search(
+ base: ldap.base_dn,
+ filter: ldap.login_filter(login),
+ attributes: ldap.search_attributes(true)
+ )
+ .map { |entry| ldap.get_user_attributes_from_ldap_entry(entry).except(:dn) }
+ end
+
+ def new_ldap_connection
+ ldap.instance_eval { initialize_ldap_con(account, account_password) }
+ end
+ end
+end
diff --git a/app/services/ldap/import_users_from_filter_service.rb b/app/services/ldap/import_users_from_filter_service.rb
new file mode 100644
index 00000000000..97dbe537770
--- /dev/null
+++ b/app/services/ldap/import_users_from_filter_service.rb
@@ -0,0 +1,30 @@
+module Ldap
+ class ImportUsersFromFilterService < BaseService
+ attr_reader :filter
+
+ def initialize(ldap, filter)
+ super(ldap)
+ @filter = filter
+ end
+
+ def perform
+ get_entries_from_filter do |entry|
+ attributes = ldap.get_user_attributes_from_ldap_entry(entry)
+ next if User.by_login(attributes[:login]).exists?
+
+ try_to_create attributes.except(:dn)
+ end
+ end
+
+ def get_entries_from_filter(&block)
+ ldap_con = new_ldap_connection
+
+ ldap_con.search(
+ base: ldap.base_dn,
+ filter: filter & ldap.default_filter,
+ attributes: ldap.search_attributes(true),
+ &block
+ )
+ end
+ end
+end
diff --git a/app/services/ldap/import_users_from_list_service.rb b/app/services/ldap/import_users_from_list_service.rb
new file mode 100644
index 00000000000..05179652f64
--- /dev/null
+++ b/app/services/ldap/import_users_from_list_service.rb
@@ -0,0 +1,35 @@
+module Ldap
+ class ImportUsersFromListService < BaseService
+ attr_reader :logins
+
+ def initialize(ldap, logins)
+ super(ldap)
+ @logins = logins
+ end
+
+ def perform
+ new_users = logins - existing_users
+
+ Rails.logger.debug { "Importing LDAP user import for #{ldap.name} for #{new_users.count} new users." }
+ import! new_users
+ end
+
+ def import!(new_users)
+ ldap_con = new_ldap_connection
+
+ new_users.each do |login|
+ synchronize_user(User.new(login: login), ldap_con)
+ rescue ::AuthSource::Error => e
+ Rails.logger.error { "Failed to synchronize user #{ldap.name} due to LDAP error: #{e.message}" }
+ # Reset the LDAP connection
+ ldap_con = new_ldap_connection
+ rescue StandardError => e
+ Rails.logger.error { "Failed to synchronize user #{ldap.name}: #{e.message}" }
+ end
+ end
+
+ def existing_users
+ User.where("LOWER(login) in (?)", logins.map(&:downcase)).pluck(:login)
+ end
+ end
+end
diff --git a/app/services/ldap/synchronize_users_service.rb b/app/services/ldap/synchronize_users_service.rb
index 401dd6768ab..c3e2e6280a8 100644
--- a/app/services/ldap/synchronize_users_service.rb
+++ b/app/services/ldap/synchronize_users_service.rb
@@ -1,9 +1,9 @@
module Ldap
- class SynchronizeUsersService
- attr_reader :ldap, :logins
+ class SynchronizeUsersService < BaseService
+ attr_reader :logins
def initialize(ldap, logins = nil)
- @ldap = ldap
+ super(ldap)
@logins = logins
end
@@ -42,54 +42,5 @@ module Ldap
ldap.users
end
end
-
- def new_ldap_connection
- ldap.instance_eval { initialize_ldap_con(account, account_password) }
- end
-
- def synchronize_user(user, ldap_con)
- Rails.logger.debug { "Synchronizing user #{user.login}." }
-
- update_attributes = user_attributes(user.login, ldap_con)
- if update_attributes
- try_to_update(user, update_attributes)
- else
- Rails.logger.info { "Could not find user #{user.login} in #{ldap.name}. Locking the user." }
- user.update_column(:status, Principal.statuses[:locked])
- end
- end
-
- # Try to create the user from attributes
- # rubocop:disable Metrics/AbcSize
- def try_to_update(user, attrs)
- call = Users::UpdateService
- .new(model: user, user: User.system)
- .call(attrs.merge)
-
- if call.success?
- # Ensure the user is activated
- call.result.update_column(:status, Principal.statuses[:active])
- Rails.logger.info { "[LDAP user sync] User '#{call.result.login}' updated" }
- else
- Rails.logger.error { "[LDAP user sync] User '#{user.login}' could not be updated: #{call.message}" }
- end
- end
- # rubocop:enable Metrics/AbcSize
-
- def user_attributes(login, ldap_con)
- # Get user login attribute and base dn which are private
- base_dn = ldap.base_dn
-
- search_attributes = ldap.search_attributes(true)
- login_filter = Net::LDAP::Filter.eq(ldap.attr_login, login)
- ldap_con.search(base: base_dn,
- filter: ldap.default_filter & login_filter,
- attributes: search_attributes) do |entry|
- data = ldap.get_user_attributes_from_ldap_entry(entry)
- return data.except(:dn)
- end
-
- nil
- end
end
end
diff --git a/lib/tasks/ldap.rake b/lib/tasks/ldap.rake
index ef372b9888a..039683da97f 100644
--- a/lib/tasks/ldap.rake
+++ b/lib/tasks/ldap.rake
@@ -39,7 +39,7 @@ namespace :ldap do
end
desc 'Synchronize existing users from the LDAP auth source' \
- 'rake ldap:sync["name=<LdapAuthSource Name>", users=<login1,login2,...>]'
+ 'rake ldap:sync name="<LdapAuthSource Name>" users=<login1,login2,...>'
task sync: :environment do
args = parse_args
ldap = LdapAuthSource.find_by!(name: args.fetch(:name))
@@ -50,6 +50,36 @@ namespace :ldap do
.call
end
+ desc 'Synchronize users from the LDAP auth source with an optional filter.' \
+ 'Note: If you omit the filter, ALL users are imported.' \
+ 'rake ldap:import_from_filter name="<LdapAuthSource Name>" filter=<Optional RFC2254 filter string>'
+ task import_from_filter: :environment do
+ args = parse_args
+ ldap = LdapAuthSource.find_by!(name: args.fetch(:name))
+
+ # Parse filter string if available
+ filter = Net::LDAP::Filter.from_rfc2254 args.fetch(:filter, 'objectClass = *')
+
+ ::Ldap::ImportUsersFromFilterService
+ .new(ldap, filter)
+ .call
+ end
+
+ desc 'Synchronize a list of user logins with the LDAP auth source' \
+ 'rake ldap:import_from_user_list name=<LdapAuthSource Name>" users=<Path to file with newline separated logins>'
+ task import_from_user_list: :environment do
+ args = parse_args
+ ldap = LdapAuthSource.find_by!(name: args.fetch(:name))
+ file = args.fetch(:users)
+
+ puts "--> Reading username file #{file}"
+ users = File.read(file).lines(chomp: true)
+
+ ::Ldap::ImportUsersFromListService
+ .new(ldap, users)
+ .call
+ end
+
desc 'Register a LDAP auth source for the given LDAP URL and attribute mapping: ' \
'rake ldap:register["url=<URL> name=<Name> onthefly=<true,false>map_{login,firstname,lastname,mail,admin}=attribute"]'
task register: :environment do
diff --git a/spec/services/ldap/import_user_list_service_integration_spec.rb b/spec/services/ldap/import_user_list_service_integration_spec.rb
new file mode 100644
index 00000000000..7b5100652ee
--- /dev/null
+++ b/spec/services/ldap/import_user_list_service_integration_spec.rb
@@ -0,0 +1,54 @@
+require 'spec_helper'
+
+describe Ldap::ImportUsersFromListService do
+ include_context 'with temporary LDAP'
+
+ subject do
+ described_class.new(auth_source, user_list).call
+ end
+
+ let(:user_list) do
+ %w[aa729 bb459 cc414]
+ end
+
+ it 'adds all three users' do
+ subject
+
+ user_aa729 = User.find_by(login: 'aa729')
+ expect(user_aa729).to be_present
+ expect(user_aa729.firstname).to eq 'Alexandra'
+ expect(user_aa729.lastname).to eq 'Adams'
+
+ user_bb459 = User.find_by(login: 'bb459')
+ expect(user_bb459).to be_present
+ expect(user_bb459.firstname).to eq 'Belle'
+ expect(user_bb459.lastname).to eq 'Baldwin'
+
+ user_cc414 = User.find_by(login: 'cc414')
+ expect(user_cc414).to be_present
+ expect(user_cc414.firstname).to eq 'Claire'
+ expect(user_cc414.lastname).to eq 'Carpenter'
+ end
+
+ context 'when two users already exist' do
+ let!(:user_aa729) { create :user, login: 'aa729', firstname: 'Foobar', auth_source: auth_source }
+ let!(:user_bb459) { create :user, login: 'bb459', firstname: 'Bla', auth_source: auth_source }
+
+ it 'adds the third one, but does not update the other two' do
+ subject
+
+ user_aa729.reload
+ user_bb459.reload
+
+ expect(user_aa729.firstname).to eq 'Foobar'
+ expect(user_aa729.lastname).to eq 'Bobbit'
+ expect(user_bb459.firstname).to eq 'Bla'
+ expect(user_bb459.lastname).to eq 'Bobbit'
+
+ user_cc414 = User.find_by(login: 'cc414')
+ expect(user_cc414).to be_present
+ expect(user_cc414.firstname).to eq 'Claire'
+ expect(user_cc414.lastname).to eq 'Carpenter'
+ end
+ end
+end
diff --git a/spec/services/ldap/import_users_from_filter_service_integration_spec.rb b/spec/services/ldap/import_users_from_filter_service_integration_spec.rb
new file mode 100644
index 00000000000..ed27e938b2b
--- /dev/null
+++ b/spec/services/ldap/import_users_from_filter_service_integration_spec.rb
@@ -0,0 +1,26 @@
+require 'spec_helper'
+
+describe Ldap::ImportUsersFromFilterService do
+ include_context 'with temporary LDAP'
+
+ subject do
+ described_class.new(auth_source, filter).call
+ end
+
+ let(:filter) { Net::LDAP::Filter.from_rfc2254 '(uid=aa729)' }
+
+ it 'adds only the matching user' do
+ subject
+
+ user_aa729 = User.find_by(login: 'aa729')
+ expect(user_aa729).to be_present
+ expect(user_aa729.firstname).to eq 'Alexandra'
+ expect(user_aa729.lastname).to eq 'Adams'
+
+ user_bb459 = User.find_by(login: 'bb459')
+ expect(user_bb459).not_to be_present
+
+ user_cc414 = User.find_by(login: 'cc414')
+ expect(user_cc414).not_to be_present
+ end
+end