gitlab-org--gitlab-foss/app/models/identity.rb
Stan Hu ab4aba7065 Fix failed LDAP logins when nil user_id present
When a LDAP user signs in the for the first time and if there
is an `Identity` object with `user_id` of `nil`, new users
will not be able to be register until that entry is cleared
because of the way identities are created:

1. First, the User object is built but not saved, so it has no `id`.
2. Then, `user.identities.build(provider: 'ldapmain')` is called,
   but it does not have an associated `user_id` as a result.
3. `User#save` is called, but the `Identity` validation fails if an
   existing entry with `user_id` of `nil` already exists.

The uniqueness validation for `nil` values doesn't make any sense in
this case. We should be enforcing this at the database level with a
foreign key constraint. To work around the issue we can validate
against the user instead, which does the right thing even when
the user isn't saved yet.

Closes https://gitlab.com/gitlab-org/gitlab-ce/issues/56734
2019-01-29 11:15:06 -08:00

48 lines
1.4 KiB
Ruby

# frozen_string_literal: true
class Identity < ActiveRecord::Base
include Sortable
include CaseSensitivity
belongs_to :user
validates :provider, presence: true
validates :extern_uid, allow_blank: true, uniqueness: { scope: UniquenessScopes.scopes, case_sensitive: false }
validates :user, uniqueness: { scope: UniquenessScopes.scopes }
before_save :ensure_normalized_extern_uid, if: :extern_uid_changed?
after_destroy :clear_user_synced_attributes, if: :user_synced_attributes_metadata_from_provider?
scope :with_provider, ->(provider) { where(provider: provider) }
scope :with_extern_uid, ->(provider, extern_uid) do
iwhere(extern_uid: normalize_uid(provider, extern_uid)).with_provider(provider)
end
def ldap?
Gitlab::Auth::OAuth::Provider.ldap_provider?(provider)
end
def self.normalize_uid(provider, uid)
if Gitlab::Auth::OAuth::Provider.ldap_provider?(provider)
Gitlab::Auth::LDAP::Person.normalize_dn(uid)
else
uid.to_s
end
end
private
def ensure_normalized_extern_uid
return if extern_uid.nil?
self.extern_uid = Identity.normalize_uid(self.provider, self.extern_uid)
end
def user_synced_attributes_metadata_from_provider?
user.user_synced_attributes_metadata&.provider == provider
end
def clear_user_synced_attributes
user.user_synced_attributes_metadata&.destroy
end
end