From 11e09e24f5de6cd0d58ec893be8133d55817bf5c Mon Sep 17 00:00:00 2001 From: Kirill Zaitsev Date: Wed, 29 Jul 2020 17:10:45 +0300 Subject: [PATCH] Add proxy support --- lib/webpush/request.rb | 12 +++++++++++- spec/webpush/request_spec.rb | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/lib/webpush/request.rb b/lib/webpush/request.rb index 26b1239..03d24f1 100644 --- a/lib/webpush/request.rb +++ b/lib/webpush/request.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true +require 'uri' require 'jwt' require 'base64' @@ -20,7 +21,7 @@ def initialize(message: '', subscription:, vapid:, **options) # rubocop:disable Metrics/AbcSize def perform - http = Net::HTTP.new(uri.host, uri.port) + http = Net::HTTP.new(uri.host, uri.port, *proxy_options) http.use_ssl = true http.ssl_timeout = @options[:ssl_timeout] unless @options[:ssl_timeout].nil? http.open_timeout = @options[:open_timeout] unless @options[:open_timeout].nil? @@ -28,6 +29,7 @@ def perform req = Net::HTTP::Post.new(uri.request_uri, headers) req.body = body + resp = http.request(req) verify_response(resp) @@ -35,6 +37,14 @@ def perform end # rubocop:enable Metrics/AbcSize + def proxy_options + return [] unless @options[:proxy] + + proxy_uri = URI.parse(@options[:proxy]) + + [proxy_uri.host, proxy_uri.port, proxy_uri.user, proxy_uri.password] + end + # rubocop:disable Metrics/MethodLength def headers headers = {} diff --git a/spec/webpush/request_spec.rb b/spec/webpush/request_spec.rb index b65bc8f..5427677 100644 --- a/spec/webpush/request_spec.rb +++ b/spec/webpush/request_spec.rb @@ -131,6 +131,20 @@ def build_request_with_api_key(endpoint, options = {}) end end + describe '#proxy_options' do + it 'returns an array of proxy options' do + request = build_request(proxy: 'http://user:password@proxy_addr:8080') + + expect(request.proxy_options).to eq(['proxy_addr', 8080, 'user', 'password']) + end + + it 'returns empty array' do + request = build_request + + expect(request.proxy_options).to be_empty + end + end + def build_request(options = {}) subscription = { endpoint: endpoint,