Common/OAuth2BaseHandler.pm

filter: Statementstmt 82.4% 80 / 97 Branchbran 62.5% 15 / 24 Conditioncond 66.6% 8 / 12 MC/DCmcdc 37.5% 3 / 8 Subroutinesub 85.0% 17 / 20 Podpod 50.0% 3 / 6 totaltotal 75.4% 126 / 167 CC 18 SCAR 14.2
CC
18
Cov
77%
prepare_request
12.0
__is_access_token_valid
7.9
initialize
4.0
CRAP 4.1
« Logging/GoogleAdsLogger.pm ↑ Summary Utils/GoogleAdsHelper.pm »
1 # Copyright 2019, Google LLC
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14  
15 package Google::Ads::GoogleAds::Common::OAuth2BaseHandler;
16  
17 11 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 11 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 11 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 11 ▶use base qw(Google::Ads::GoogleAds::Common::AuthHandlerInterface);
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 # The following needs to be on one line because CPAN uses a particularly hacky
23 # eval() to determine module versions.
24 11 ▶use Google::Ads::GoogleAds::Constants; our $VERSION = ${Google::Ads::GoogleAds::Constants::VERSION};
Subroutine BEGIN: called CC=1 SCAR=0.0
25  
26 11 ▶use Class::Std::Fast;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 11 ▶use HTTP::Request::Common;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 11 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 11 ▶use URI::Escape;
Subroutine BEGIN: called CC=1 SCAR=0.0
30  
31 # Class::Std-style attributes. Need to be kept in the same line.
32 # These need to go in the same line for older Perl interpreters to understand.
33 11 my %api_client_of : ATTR(:name<api_client> :default<>);
34 11 my %client_id_of : ATTR(:name<client_id> :default<>);
35 11 my %access_token_of : ATTR(:init_arg<access_token> :default<>);
36 11 my %access_token_expires_of : ATTR(:name<access_token_expires> :default<>);
37 11 my %__lwp_agent_of : ATTR(:name<__lwp_agent> :default<>);
38  
39 # Constructor.
40 18 ▶sub START {
Subroutine START: called CC=2 SCAR=7.1
Pod undocumented
41 18 my ($self, $ident) = @_;
42  
43 18 ▶ $__lwp_agent_of{$ident} ||= LWP::UserAgent->new();
Condition66%2/3
$__lwp_agent_of{$ident} ||= "LWP::UserAgent"->new
l!l&&r!l&&!r
2160
MC/DC0%0/2
$__lwp_agent_of{$ident} ||= "LWP::UserAgent"->new
$__lwp_agent_of{$ident} "LWP::UserAgent"->new
Truth table66%2/3
A ||= B
A= $__lwp_agent_of{$ident}B= "LWP::UserAgent"->new
ABresult
1X1
011
000
44 }
45  
46 # Methods from Google::Ads::GoogleAds::Common::AuthHandlerInterface.
47 18 ▶sub initialize : CUMULATIVE(BASE FIRST) {
Subroutine initialize: called CC=4 SCAR=14.0
Pod documented
48 18 my ($self, $api_client, $properties) = @_;
49 18 my $ident = ident $self;
50  
51 18 $api_client_of{$ident} = $api_client;
52 $client_id_of{$ident} = $properties->{clientId}
53 18 ▶ || $client_id_of{$ident};
Condition66%2/3
$properties->{'clientId'} || $client_id_of{$ident}
l!l&&r!l&&!r
1305
MC/DC50%1/2
$properties->{'clientId'} || $client_id_of{$ident}
$properties->{'clientId'} $client_id_of{$ident}
Truth table66%2/3
A || B
A= $properties->{'clientId'}B= $client_id_of{$ident}
ABresult
1X1
011
000
54 $access_token_of{$ident} = $properties->{accessToken}
55 18 ▶ || $access_token_of{$ident};
Condition66%2/3
$properties->{'accessToken'} || $access_token_of{$ident}
l!l&&r!l&&!r
2016
MC/DC50%1/2
$properties->{'accessToken'} || $access_token_of{$ident}
$properties->{'accessToken'} $access_token_of{$ident}
Truth table66%2/3
A || B
A= $properties->{'accessToken'}B= $access_token_of{$ident}
ABresult
1X1
011
000
56  
57 # Set up proxy for __lwp_agent.
58 18 my $proxy = $api_client->get_proxy();
59 $proxy
60 ? $__lwp_agent_of{$ident}->proxy(['http', 'https'], $proxy)
61 18 ▶ : $__lwp_agent_of{$ident}->env_proxy;
Branch: 1 branch
BranchTrueFalseTotal
$proxy ? : 14 4 18
62 11 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
63  
64 0 ▶sub prepare_request {
Subroutine prepare_request: not called CC=3 SCAR=24.8
Pod documented
65 0 my ($self, $http_method, $request_url, $http_headers, $request_content) = @_;
66  
67 0 my $access_token = $self->get_access_token();
68  
69 0 ▶ if (!$access_token) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($access_token) 0 0 0
70 0 my $api_client = $self->get_api_client();
71 0 my $err_msg =
72 "Unable to prepare a request, authorization info is " .
73 "incomplete or invalid.";
74 0 ▶ $api_client->get_die_on_faults() ? die($err_msg) : warn($err_msg);
Branch: 1 branch
BranchTrueFalseTotal
$api_client->get_die_on_faults ? : 0 0 0
75 0 return;
76 }
77  
78 0 push @$http_headers, ("Authorization", "Bearer ${access_token}");
79  
80 0 return HTTP::Request->new($http_method, $request_url, $http_headers,
81 $request_content);
82 }
83  
84 3 ▶sub is_auth_enabled {
Subroutine is_auth_enabled: called CC=1 SCAR=0.0
Pod documented
85 3 my $self = shift;
86  
87 3 return $self->get_access_token();
88 }
89  
90 # Custom getter and setter for the access_token with logic to auto-refresh.
91 6 ▶sub get_access_token {
Subroutine get_access_token: called CC=3 SCAR=11.2
Pod undocumented
92 6 my $self = shift;
93 6 my $ident = ident $self;
94  
95 6 ▶ if (!$self->__is_access_token_valid()) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->__is_access_token_valid) 2 4 6
96 2 ▶ if (!$self->_refresh_access_token()) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_refresh_access_token) 2 0 2
97 2 return undef;
98 }
99  
100 0 return $access_token_of{$ident};
101 }
102  
103 4 return $access_token_of{$ident};
104 }
105  
106 1 ▶sub set_access_token {
Subroutine set_access_token: called CC=1 SCAR=0.0
Pod undocumented
107 1 my ($self, $token) = @_;
108  
109 1 $access_token_of{ident $self} = $token;
110 1 $access_token_expires_of{ident $self} = undef;
111 }
112  
113 # Internal methods.
114  
115 # Checks if:
116 # - the access token is set
117 # - if the token has no expiration set then assumes it was manually set and:
118 # - checks the token info, if it is valid then sets its expiration
119 # - checks the token scopes
120 # - checks the token has not expired
121 6 ▶sub __is_access_token_valid {
Subroutine __is_access_token_valid: called CC=7 SCAR=20.7
122 6 my $self = shift;
123 6 my $ident = ident $self;
124  
125 6 my $access_token = $access_token_of{$ident};
126 6 ▶ if (!$access_token) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($access_token) 2 4 6
127 2 return 0;
128 }
129  
130 4 ▶ if (!$self->get_access_token_expires()) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->get_access_token_expires) 2 2 4
131 2 my $url =
132 Google::Ads::GoogleAds::Constants::OAUTH2_TOKEN_INFO_URL .
133 "?access_token=" . uri_escape($access_token);
134 2 my $response = $self->get___lwp_agent()->request(GET $url);
135 2 ▶ if (!$response->is_success()) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 0 2 2
136 0 my $err_msg = $response->decoded_content();
137 0 ▶ $self->get_api_client()->get_die_on_faults()
Branch: 1 branch
BranchTrueFalseTotal
$self->get_api_client->get_die_on_faults ? : 0 0 0
138 ? die($err_msg)
139 : warn($err_msg);
140 0 return 0;
141 }
142 2 my $content_hash =
143 $self->__parse_auth_response($response->decoded_content());
144 2 my %token_scopes = map { $_ => 1 } split(" ", $content_hash->{scope});
145  
146 2 foreach my $required_scope ($self->_scope()) {
147 4 ▶ if (!exists($token_scopes{$required_scope})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $token_scopes{$required_scope}) 0 4 4
148 0 return 0;
149 }
150 }
151 2 $self->set_access_token_expires(time + $content_hash->{expires_in});
152 }
153  
154 4 return time < ($self->get_access_token_expires() - 10);
155 }
156  
157 3 ▶sub __parse_auth_response {
Subroutine __parse_auth_response: called CC=4 SCAR=13.9
158 3 my ($self, $response_content) = @_;
159  
160 3 my %content_hash = ();
161  
162 # Use below regex to parse the token info response into hash.
163 # The sample token info response is as below:
164 # {
165 # "issued_to": "1234567890-abcdefg.apps.googleusercontent.com",
166 # "audience": "1234567890-abcdefg.apps.googleusercontent.com",
167 # "scope": "https://www.googleapis.com/auth/adwords",
168 # "expires_in": 3548
169 # }
170 3 ▶ while (
Branch: 1 branch
BranchTrueFalseTotal
if ($response_content =~ /([^"]+)"\s*:\s*"([^"]+)|([^"]+)"\s*:\s*([0-9]+)/g) 7 3 10
171 $response_content =~ m/([^"]+)"\s*:\s*"([^"]+)|([^"]+)"\s*:\s*([0-9]+)/g)
172 {
173 7 ▶ if ($1 && $2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($1 and $2) { } 4 3 7
Condition66%2/3
$1 and $2
!ll&&!rl&&r
304
MC/DC50%1/2
$1 and $2
$1 $2
Truth table66%2/3
A and B
A= $1B= $2
ABresult
0X0
100
111
174 4 $content_hash{$1} = $2;
175 } else {
176 3 $content_hash{$3} = $4;
177 }
178 }
179  
180 3 return \%content_hash;
181 }
182  
183 # Meant to be implemented by a concrete class, which should return the required
184 # API scopes in an array for the OAuth2 protocol.
185 0 ▶sub _scope {
Subroutine _scope: not called CC=1 SCAR=6.9
186 0 my $self = shift;
187 0 die "Need to be implemented by subclass";
188 }
189  
190 # Method called to refresh the stored OAuth2 access token. Implementors will issue
191 # an access token refresh request to the OAuth2 server.
192 0 ▶sub _refresh_access_token {
Subroutine _refresh_access_token: not called CC=1 SCAR=6.9
193 0 die "Need to be implemented by subclass";
194 }
195  
196 11 1;
197  
198 =pod
199  
200 =head1 NAME
201  
202 Google::Ads::GoogleAds::Common::OAuth2BaseHandler
203  
204 =head1 DESCRIPTION
205  
206 An abstract base implementation that defines part of the logic required to use
207 OAuth2 against Google APIs.
208  
209 It is meant to be specialized and its L</_scope>, L</_refresh_access_token>
210 methods should be properly implemented.
211  
212 =head1 ATTRIBUTES
213  
214 Each of these attributes can be set via
215 Google::Ads::GoogleAds::Common::OAuth2BaseHandler->new().
216  
217 Alternatively, there is a get_ and set_ method associated with each attribute
218 for retrieving or setting them dynamically.
219  
220 my %api_client_of : ATTR(:name<api_client> :default<>);
221 my %client_id_of : ATTR(:name<client_id> :default<>);
222 my %access_token_of : ATTR(:init_arg<access_token> :default<>);
223 my %access_token_expires_of : ATTR(:name<access_token_expires> :default<>);
224  
225 =head2 api_client
226  
227 A reference to the API client used to handle the API requests.
228  
229 =head2 client_id
230  
231 OAuth2 client id obtained from the Google APIs console.
232  
233 =head2 access_token
234  
235 Stores an OAuth2 access token after the authorization flow is followed or for
236 you to manually set it in case you had it previously stored. If this is manually
237 set this handler will verify its validity before preparing a request.
238  
239 =head1 METHODS
240  
241 =head2 initialize
242  
243 Initializes the handler with the API client object and the properties such as
244 client_id and access_token.
245  
246 =head3 Parameters
247  
248 =over
249  
250 =item *
251  
252 A required I<api_client> with a reference to the API client object handling the
253 requests against the API.
254  
255 =item *
256  
257 A hash reference with the following keys.
258  
259 {
260 clientId => "client-id",
261 accessToken => "access-token"
262 }
263  
264 Refer to the documentation of the L</client_id> and L</access_token> properties.
265  
266 =back
267  
268 =head2 prepare_request
269  
270 Refer to L<Google::Ads::GoogleAds::Common::AuthHandlerInterface> documentation
271 of this method.
272  
273 =head2 is_auth_enabled
274  
275 Refer to L<Google::Ads::GoogleAds::Common::AuthHandlerInterface> documentation
276 of this method.
277  
278 =head2 _scope
279  
280 Meant to be implemented by a concrete class, which should return the required
281 API scopes in an array for the OAuth2 protocol.
282  
283 =head2 _refresh_access_token
284  
285 Method called to refresh the stored OAuth2 access token. Implementors will issue
286 an access token refresh request to the OAuth2 server.
287  
288 =head1 LICENSE AND COPYRIGHT
289  
290 Copyright 2019 Google LLC
291  
292 Licensed under the Apache License, Version 2.0 (the "License");
293 you may not use this file except in compliance with the License.
294 You may obtain a copy of the License at
295  
296 http://www.apache.org/licenses/LICENSE-2.0
297  
298 Unless required by applicable law or agreed to in writing, software
299 distributed under the License is distributed on an "AS IS" BASIS,
300 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
301 See the License for the specific language governing permissions and
302 limitations under the License.
303  
304 =head1 REPOSITORY INFORMATION
305  
306 $Rev: $
307 $LastChangedBy: $
308 $Id: $
309  
310 =cut
« Logging/GoogleAdsLogger.pm ↑ Summary Utils/GoogleAdsHelper.pm »