summaryrefslogtreecommitdiff
path: root/lib/gitlab/ldap/user.rb
blob: 1ea7751e27dd0b7f9ec0a59e29a202a2972a5718 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
require 'gitlab/o_auth/user'

# LDAP extension for User model
#
# * Find or create user from omniauth.auth data
# * Links LDAP account with existing user
# * Auth LDAP user with login and password
#
module Gitlab
  module LDAP
    class User < Gitlab::OAuth::User
      class << self
        def find_by_uid_and_provider(uid, provider)
          # LDAP distinguished name is case-insensitive
          identity = ::Identity.
            where(provider: provider).
            where('lower(extern_uid) = ?', uid.mb_chars.downcase.to_s).last
          identity && identity.user
        end
      end

      def initialize(auth_hash)
        super
        update_user_attributes
      end

      # instance methods
      def gl_user
        @gl_user ||= find_by_uid_and_provider || find_by_email || build_new_user
      end

      def find_by_uid_and_provider
        self.class.find_by_uid_and_provider(
          auth_hash.uid.downcase, auth_hash.provider)
      end

      def find_by_email
        ::User.find_by(email: auth_hash.email)
      end

      def update_user_attributes
        return unless persisted?

        gl_user.skip_reconfirmation!
        gl_user.email = auth_hash.email

        # 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)
        
        # For a new user set extern_uid to the LDAP DN
        # For an existing user with matching email but changed DN, update the DN.
        # For an existing user with no change in DN, this line changes nothing.
        identity.extern_uid = auth_hash.uid

        gl_user
      end

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

      def block_after_signup?
        ldap_config.block_auto_created_users
      end

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

      def ldap_config
        Gitlab::LDAP::Config.new(auth_hash.provider)
      end

      def auth_hash=(auth_hash)
        @auth_hash = Gitlab::LDAP::AuthHash.new(auth_hash)
      end
    end
  end
end