encrypted.rb 1.4 KB
Newer Older
1 2 3 4 5 6 7
# frozen_string_literal: true

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

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

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

      token_authenticatable
    end

    def get_token(instance)
21
      raw_token = instance.read_attribute(encrypted_field)
22
      token = Gitlab::CryptoHelper.aes256_gcm_decrypt(raw_token)
23 24

      token || (fallback_strategy.get_token(instance) if fallback?)
25 26 27
    end

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

30
      instance[encrypted_field] = Gitlab::CryptoHelper.aes256_gcm_encrypt(token)
31
      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