user.rb 2.0 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).
17
            where('lower(extern_uid) = ?', uid.downcase).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(
34
          auth_hash.uid.downcase, auth_hash.provider)
35 36 37
      end

      def find_by_email
38
        ::User.find_by(email: auth_hash.email)
39 40 41
      end

      def update_user_attributes
42 43
        return unless persisted?

44
        gl_user.skip_reconfirmation!
45
        gl_user.email = auth_hash.email
46

47 48 49 50 51 52 53
        # If we don't have an identity for this provider yet, create one
        if gl_user.identities.find_by(provider: auth_hash.provider).nil?
          gl_user.identities.new(extern_uid: auth_hash.uid, provider: auth_hash.provider)
        else # Update the UID attribute for this provider in case it has changed
          identity = gl_user.identities.select { |identity|  identity.provider == auth_hash.provider }
          identity.first.extern_uid = auth_hash.uid
        end
54

55
        gl_user
56 57 58
      end

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

62 63
      def block_after_signup?
        ldap_config.block_auto_created_users
64
      end
65 66 67 68

      def allowed?
        Gitlab::LDAP::Access.allowed?(gl_user)
      end
69 70 71 72

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