summaryrefslogtreecommitdiff
path: root/app/models/concerns/token_authenticatable_strategies/digest.rb
blob: 9926662ed665b4d8f1fa2ef8c88e905fdd5769f4 (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
# frozen_string_literal: true

module TokenAuthenticatableStrategies
  class Digest < Base
    def find_token_authenticatable(token, unscoped = false)
      return unless token

      token_authenticatable = relation(unscoped).find_by(token_field_name => Gitlab::CryptoHelper.sha256(token))

      if @options[:fallback]
        token_authenticatable ||= fallback_strategy.find_token_authenticatable(token)
      end

      token_authenticatable
    end

    def get_token(instance)
      token = instance.cleartext_tokens&.[](@token_field)
      token ||= fallback_strategy.get_token(instance) if @options[:fallback]

      token
    end

    def set_token(instance, token)
      return unless token

      instance.cleartext_tokens ||= {}
      instance.cleartext_tokens[@token_field] = token
      instance[token_field_name] = Gitlab::CryptoHelper.sha256(token)
      instance[@token_field] = nil if @options[:fallback]
    end

    protected

    def fallback_strategy
      @fallback_strategy ||= TokenAuthenticatableStrategies::Insecure.new(@klass, @token_field, @options)
    end

    def token_set?(instance)
      token_digest = instance.read_attribute(token_field_name)
      token_digest ||= instance.read_attribute(@token_field) if @options[:fallback]

      token_digest.present?
    end

    def token_field_name
      "#{@token_field}_digest"
    end
  end
end