user.rb 2.27 KB
Newer Older
1
require 'gitlab/o_auth/user'
2

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

22 23 24 25
      def initialize(auth_hash)
        super
        update_user_attributes
      end
26

27 28 29 30
      # instance methods
      def gl_user
        @gl_user ||= find_by_uid_and_provider || find_by_email || build_new_user
      end
31

32
      def find_by_uid_and_provider
33
        self.class.find_by_uid_and_provider(auth_hash.uid, auth_hash.provider)
34 35 36
      end

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

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

47 48 49
          # 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)
50

51 52 53 54 55
          # 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
Douwe Maan's avatar
Douwe Maan committed
56

57
        gl_user.ldap_email = auth_hash.has_email?
58

59
        gl_user
60 61 62
      end

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

66 67
      def block_after_signup?
        ldap_config.block_auto_created_users
68
      end
69 70 71 72

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

Douwe Maan's avatar
Douwe Maan committed
74 75
      def ldap_config
        Gitlab::LDAP::Config.new(auth_hash.provider)
76
      end
77 78

      def auth_hash=(auth_hash)
Douwe Maan's avatar
Douwe Maan committed
79
        @auth_hash = Gitlab::LDAP::AuthHash.new(auth_hash)
80
      end
81 82 83
    end
  end
end