summaryrefslogtreecommitdiff
path: root/lib/gitlab/external_authorization/access.rb
blob: e111c41fcc2f39a6d9b1ca762590c471b24a5836 (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
# frozen_string_literal: true

module Gitlab
  module ExternalAuthorization
    class Access
      attr_reader :user,
                  :reason,
                  :loaded_at,
                  :label,
                  :load_type

      def initialize(user, label)
        @user, @label = user, label
      end

      def loaded?
        loaded_at && (loaded_at > ExternalAuthorization::Cache::VALIDITY_TIME.ago)
      end

      def has_access?
        @access
      end

      def load!
        load_from_cache
        load_from_service unless loaded?
        self
      end

      private

      def load_from_cache
        @load_type = :cache
        @access, @reason, @loaded_at = cache.load
      end

      def load_from_service
        @load_type = :request
        response = Client.new(@user, @label).request_access
        @access = response.successful?
        @reason = response.reason
        @loaded_at = Time.now
        cache.store(@access, @reason, @loaded_at) if response.valid?
      rescue ::Gitlab::ExternalAuthorization::RequestFailed => e
        @access = false
        @reason = e.message
        @loaded_at = Time.now
      end

      def cache
        @cache ||= ExternalAuthorization::Cache.new(@user, @label)
      end
    end
  end
end