encrypted.rb 1.4 KB
Newer Older
1 2
# frozen_string_literal: true

3 4
          @parallelizable.with_indifferent_access

5 6 7 8 9
module TokenAuthenticatableStrategies
  class Encrypted < Base
    def find_token_authenticatable(token, unscoped = false)
      return unless token

10
      encrypted_value = Gitlab::CryptoHelper.aes256_gcm_encrypt(token)
11
      token_authenticatable = relation(unscoped)
12
        .find_by(encrypted_field => encrypted_value)
13

14 15 16
      if fallback?
        token_authenticatable ||= fallback_strategy
          .find_token_authenticatable(token)
17 18 19 20 21 22
      end

      token_authenticatable
    end

    def get_token(instance)
23
      raw_token = instance.read_attribute(encrypted_field)
24
      token = Gitlab::CryptoHelper.aes256_gcm_decrypt(raw_token)
25
      token ||= fallback_strategy.get_token(instance) if fallback?
26 27 28
    end

    def set_token(instance, token)
29
      raise ArgumentError unless token.present?
30

31
      instance[encrypted_field] = Gitlab::CryptoHelper.aes256_gcm_encrypt(token)
32 33 34 35 36
    end

    protected

    def fallback_strategy
37
      @fallback_strategy ||= TokenAuthenticatableStrategies::Insecure
38
        .new(klass, token_field, options)
39 40 41
    end

    def token_set?(instance)
42 43
      raw_token = instance.read_attribute(encrypted_field)
      raw_token ||= instance.read_attribute(token_field) if fallback?
44

45
      raw_token.present?
46 47
    end

48 49
    def encrypted_field
      @encrypted_field ||= "#{@token_field}_encrypted"
50 51 52
    end
  end
end