diff --git a/app/models/virtual_registries/packages/maven/upstream.rb b/app/models/virtual_registries/packages/maven/upstream.rb index 16f1a4187ef436b4f8d2e3125a37c233c7df76f3..db1e41b5f7594c124ba069216e8ed2fa889f7674 100644 --- a/app/models/virtual_registries/packages/maven/upstream.rb +++ b/app/models/virtual_registries/packages/maven/upstream.rb @@ -31,17 +31,33 @@ class Upstream < ApplicationRecord validates :url, :username, :password, length: { maximum: 255 } after_initialize :read_credentials + after_validation :reset_credentials, if: -> { persisted? && url_changed? } before_save :write_credentials private def read_credentials + self.credentials ||= {} + + # if credentials are blank we might have a username + password from initializer. Don't reset them. + return if credentials.blank? + self.username, self.password = (credentials || {}).values_at('username', 'password') + clear_username_change + clear_password_change end def write_credentials self.credentials = (credentials || {}).merge('username' => username, 'password' => password) end + + def reset_credentials + return if username_changed? && password_changed? + + self.username = nil + self.password = nil + self.credentials = {} + end end end end diff --git a/spec/models/virtual_registries/packages/maven/upstream_spec.rb b/spec/models/virtual_registries/packages/maven/upstream_spec.rb index adb8be2817829b380412ea2a348de13143cc13e0..d94be8b01c6e30b1550d344799f07553e5e60529 100644 --- a/spec/models/virtual_registries/packages/maven/upstream_spec.rb +++ b/spec/models/virtual_registries/packages/maven/upstream_spec.rb @@ -94,6 +94,32 @@ end end end + + context 'when url is updated' do + where(:new_url, :new_user, :new_pwd, :expected_user, :expected_pwd, :expected_credentials) do + 'http://original_url.test' | 'test' | 'test' | 'test' | 'test' | { 'username' => 'test', 'password' => 'test' } + 'http://update_url.test' | 'test' | 'test' | 'test' | 'test' | { 'username' => 'test', 'password' => 'test' } + 'http://update_url.test' | :none | :none | nil | nil | { 'username' => nil, 'password' => nil } + 'http://update_url.test' | 'test' | :none | nil | nil | { 'username' => nil, 'password' => nil } + 'http://update_url.test' | :none | 'test' | nil | nil | { 'username' => nil, 'password' => nil } + end + + with_them do + before do + upstream.update!(url: 'http://original_url.test', username: 'original_user', password: 'original_pwd') + end + + it 'resets the username and the password when necessary' do + new_attributes = { url: new_url, username: new_user, password: new_pwd }.select { |_, v| v != :none } + upstream.update!(new_attributes) + + expect(upstream.reload.url).to eq(new_url) + expect(upstream.username).to eq(expected_user) + expect(upstream.password).to eq(expected_pwd) + expect(upstream.credentials).to eq(expected_credentials) + end + end + end end end