<commit_before>class ValidateAuthorizationHeader
  attr_reader :public_key

  def initialize(app)
    @app = app
    @public_key = PublicKey.new
  end

  def call(env)
    if env['HTTP_AUTHORIZATION'] =~ /\ABearer/
        token = env['HTTP_AUTHORIZATION'].split[1]
        @public_key.refresh_key
      begin
        claims = JSON::JWT.decode(token, @public_key.key)
      rescue JSON::JWT::VerificationFailed => e
        [401, {'Content-Type' => 'application/json'}, [{status: 401, error: 'Invalid JSON Web Token'}.to_json]]
      else
        env['prx.auth'] = claims

        @app.call(env)
      end
    else
      @app.call(env)
    end
  end

  class PublicKey
    attr_reader :key

    EXPIRES_IN = 12.hours
    AUTH_URI = URI('https://auth.prx.org/api/v1/certs')

    def initialize
      @created_at = Time.now
      get_key
    end

    def refresh_key
      if Time.now > @created_at + EXPIRES_IN
        get_key
      end
    end

    def get_key
      certs = JSON.parse(Net::HTTP.get(AUTH_URI))
      cert_string = certs["certificates"].values[0]
      certificate = OpenSSL::X509::Certificate.new(cert_string)
      @key = certificate.public_key
    end
  end
end<commit_msg>move refresh_key method into PublicKey#key<commit_after>class ValidateAuthorizationHeader
  attr_reader :public_key

  def initialize(app)
    @app = app
    @public_key = PublicKey.new
  end

  def call(env)
    if env['HTTP_AUTHORIZATION'] =~ /\ABearer/
        token = env['HTTP_AUTHORIZATION'].split[1]
      begin
        claims = JSON::JWT.decode(token, @public_key.key)
      rescue JSON::JWT::VerificationFailed => e
        [401, {'Content-Type' => 'application/json'}, [{status: 401, error: 'Invalid JSON Web Token'}.to_json]]
      else
        env['prx.auth'] = claims

        @app.call(env)
      end
    else
      @app.call(env)
    end
  end

  class PublicKey
    EXPIRES_IN = 12.hours
    AUTH_URI = URI('https://auth.prx.org/api/v1/certs')

    def initialize
      @created_at = Time.now
      get_key
    end

    def refresh_key
      if Time.now > @created_at + EXPIRES_IN
        get_key
      end
    end

    def get_key
      certs = JSON.parse(Net::HTTP.get(AUTH_URI))
      cert_string = certs["certificates"].values[0]
      certificate = OpenSSL::X509::Certificate.new(cert_string)
      @key = certificate.public_key
    end

    def key
      refresh_key
      @key
    end
  end
end
{'fraction_non_alphanumeric': 0.11249481112494811, 'fraction_numerical': 0.011623080116230802, 'mean_word_length': 2.4927536231884058, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 9, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5036553', 'n_tokens_mistral': 839, 'n_tokens_neox': 810, 'n_words': 167}