summaryrefslogtreecommitdiff
path: root/lib/gitlab/ldap/access.rb
blob: 4e75729ca73cd62dcb7b94bf29d70a46f6aa76d2 (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
81
82
83
84
85
86
87
# LDAP authorization model
#
# * Check if we are allowed access (not blocked)
#
module Gitlab
  module LDAP
    class Access
      attr_reader :provider, :user

      def self.open(user, &block)
        Gitlab::LDAP::Adapter.open(user.ldap_identity.provider) do |adapter|
          block.call(self.new(user, adapter))
        end
      end

      def self.allowed?(user)
        self.open(user) do |access|
          if access.allowed?
            Users::UpdateService.new(user, user, last_credential_check_at: Time.now).execute

            true
          else
            false
          end
        end
      end

      def initialize(user, adapter = nil)
        @adapter = adapter
        @user = user
        @provider = user.ldap_identity.provider
      end

      def allowed?
        if ldap_user
          unless ldap_config.active_directory
            unblock_user(user, 'is available again') if user.ldap_blocked?
            return true
          end

          # Block user in GitLab if he/she was blocked in AD
          if Gitlab::LDAP::Person.disabled_via_active_directory?(user.ldap_identity.extern_uid, adapter)
            block_user(user, 'is disabled in Active Directory')
            false
          else
            unblock_user(user, 'is not disabled anymore') if user.ldap_blocked?
            true
          end
        else
          # Block the user if they no longer exist in LDAP/AD
          block_user(user, 'does not exist anymore')
          false
        end
      end

      def adapter
        @adapter ||= Gitlab::LDAP::Adapter.new(provider)
      end

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

      def ldap_user
        @ldap_user ||= Gitlab::LDAP::Person.find_by_dn(user.ldap_identity.extern_uid, adapter)
      end

      def block_user(user, reason)
        user.ldap_block

        Gitlab::AppLogger.info(
          "LDAP account \"#{user.ldap_identity.extern_uid}\" #{reason}, " \
          "blocking Gitlab user \"#{user.name}\" (#{user.email})"
        )
      end

      def unblock_user(user, reason)
        user.activate

        Gitlab::AppLogger.info(
          "LDAP account \"#{user.ldap_identity.extern_uid}\" #{reason}, " \
          "unblocking Gitlab user \"#{user.name}\" (#{user.email})"
        )
      end
    end
  end
end