user.rb 2.3 KB
Newer Older
1 2 3 4
# LDAP extension for User model
#
# * Find or create user from omniauth.auth data
# * Links LDAP account with existing user
5
# * Auth LDAP user with login and password
6 7 8
#
module Gitlab
  module LDAP
9
    class User < Gitlab::OAuth::User
10
      class << self
11
        def find_by_uid_and_provider(uid, provider)
12
          # LDAP distinguished name is case-insensitive
13
          identity = ::Identity.
14
            where(provider: provider).
D
Douwe Maan 已提交
15
            iwhere(extern_uid: uid).last
16
          identity && identity.user
17
        end
18
      end
19

20 21 22 23
      def initialize(auth_hash)
        super
        update_user_attributes
      end
24

25 26 27 28
      def save
        super('LDAP')
      end

29 30 31 32
      # instance methods
      def gl_user
        @gl_user ||= find_by_uid_and_provider || find_by_email || build_new_user
      end
33

34
      def find_by_uid_and_provider
35
        self.class.find_by_uid_and_provider(auth_hash.uid, auth_hash.provider)
36 37 38
      end

      def find_by_email
39
        ::User.find_by(email: auth_hash.email.downcase) if auth_hash.has_email?
40 41 42
      end

      def update_user_attributes
43 44 45 46 47
        if persisted?
          if auth_hash.has_email?
            gl_user.skip_reconfirmation!
            gl_user.email = auth_hash.email
          end
48

49 50 51
          # find_or_initialize_by doesn't update `gl_user.identities`, and isn't autosaved.
          identity = gl_user.identities.find { |identity|  identity.provider == auth_hash.provider }
          identity ||= gl_user.identities.build(provider: auth_hash.provider)
52

53 54 55 56 57
          # For a new identity set extern_uid to the LDAP DN
          # For an existing identity with matching email but changed DN, update the DN.
          # For an existing identity with no change in DN, this line changes nothing.
          identity.extern_uid = auth_hash.uid
        end
D
Douwe Maan 已提交
58

59
        gl_user.ldap_email = auth_hash.has_email?
60

61
        gl_user
62 63 64
      end

      def changed?
65
        gl_user.changed? || gl_user.identities.any?(&:changed?)
66
      end
67

68 69
      def block_after_signup?
        ldap_config.block_auto_created_users
70
      end
71 72 73 74

      def allowed?
        Gitlab::LDAP::Access.allowed?(gl_user)
      end
75

D
Douwe Maan 已提交
76 77
      def ldap_config
        Gitlab::LDAP::Config.new(auth_hash.provider)
78
      end
79 80

      def auth_hash=(auth_hash)
D
Douwe Maan 已提交
81
        @auth_hash = Gitlab::LDAP::AuthHash.new(auth_hash)
82
      end
83 84 85
    end
  end
end