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

module Gitlab
  module ExternalAuthorization
    class Cache
      VALIDITY_TIME = 6.hours

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

      def load
        @access, @reason, @refreshed_at = ::Gitlab::Redis::Cache.with do |redis|
          redis.hmget(cache_key, :access, :reason, :refreshed_at)
        end

        [access, reason, refreshed_at]
      end

      def store(new_access, new_reason, new_refreshed_at)
        ::Gitlab::Redis::Cache.with do |redis|
          redis.pipelined do
            redis.mapped_hmset(
              cache_key,
              {
                access: new_access.to_s,
                reason: new_reason.to_s,
                refreshed_at: new_refreshed_at.to_s
              }
            )

            redis.expire(cache_key, VALIDITY_TIME)
          end
        end
      end

      private

      def access
        ::Gitlab::Utils.to_boolean(@access)
      end

      def reason
        # `nil` if the cached value was an empty string
        return unless @reason.present?

        @reason
      end

      def refreshed_at
        # Don't try to parse a time if there was no cache
        return unless @refreshed_at.present?

        Time.parse(@refreshed_at)
      end

      def cache_key
        "external_authorization:user-#{@user.id}:label-#{@label}"
      end
    end
  end
end