Cmdline.pm

filter: Statementstmt 33.8% 46 / 136 Branchbran 0.0% 0 / 28 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 42.3% 11 / 26 Podpod 20.0% 3 / 15 totaltotal 28.5% 60 / 210 CC 16 SCAR 20.8
CC
16
Cov
28%
http_get
20.0
client_init_conf_check
20.0
full_login_uri
12.0
CRAP 8.0
↑ Summary Cmdline/Automatic.pm »
1 ###########################################
2 package OAuth::Cmdline;
3 ###########################################
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use YAML qw( DumpFile LoadFile );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use HTTP::Request::Common;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Log::Log4perl qw(:easy);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use JSON qw( from_json );
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use MIME::Base64;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 1 our $VERSION = "0.05";
17  
18 1 has client_id => ( is => "rw" );
19 1 has client_secret => ( is => "rw" );
20 1 has local_uri => (
21 is => "rw",
22 default => "http://localhost:8082",
23 );
24 1 has homedir => (
25 is => "ro",
26 default => glob '~',
27 );
28 1 has login_uri => ( is => "rw" );
29 1 has site => ( is => "rw" );
30 1 has scope => ( is => "rw" );
31 1 has token_uri => ( is => "rw" );
32 1 has redir_uri => ( is => "rw" );
33 1 has access_type => ( is => "rw" );
34 1 has raise_error => ( is => "rw" );
35  
36 ###########################################
37 sub redirect_uri {
38 ###########################################
39 0 ▶ my( $self ) = @_;
Subroutine redirect_uri: not called CC=1 SCAR=6.9
Pod undocumented
40  
41 0 return $self->local_uri . "/callback";
42 }
43  
44 ###########################################
45 sub cache_file_path {
46 ###########################################
47 0 ▶ my( $self ) = @_;
Subroutine cache_file_path: not called CC=1 SCAR=6.9
Pod undocumented
48  
49 # creds saved ~/.[site].yml
50 0 return $self->homedir . "/." .
51 $self->site . ".yml";
52 }
53  
54 ###########################################
55 sub full_login_uri {
56 ###########################################
57 0 ▶ my( $self ) = @_;
Subroutine full_login_uri: not called CC=3 SCAR=24.8
Pod undocumented
58  
59 0 my $full_login_uri = URI->new( $self->login_uri );
60  
61 0 ▶ $full_login_uri->query_form (
Branch: 2 branches
BranchTrueFalseTotal
defined $self->redirect_uri ? : 0 0 0
$self->access_type ? : 0 0 0
62 client_id => $self->client_id(),
63 response_type => "code",
64 (defined $self->redirect_uri() ?
65 ( redirect_uri => $self->redirect_uri() ) :
66 ()
67 ),
68 scope => $self->scope(),
69 ($self->access_type() ?
70 (access_type => $self->access_type()) : ()),
71 );
72  
73 0 DEBUG "full login uri: $full_login_uri";
74 0 return $full_login_uri;
75 }
76  
77 ###########################################
78 sub access_token {
79 ###########################################
80 0 ▶ my( $self ) = @_;
Subroutine access_token: not called CC=3 SCAR=24.8
Pod undocumented
81  
82 0 ▶ if( $self->token_expired() ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->token_expired) 0 0 0
83 0 ▶ $self->token_refresh() or LOGDIE "Token refresh failed";
Branch: 1 branch
BranchTrueFalseTotal
$self->token_refresh or LOGDIE("Token refresh failed") 0 0 0
84 }
85  
86 0 my $cache = $self->cache_read();
87 0 return $cache->{ access_token };
88 }
89  
90 ###########################################
91 sub authorization_headers {
92 ###########################################
93 0 ▶ my( $self ) = @_;
Subroutine authorization_headers: not called CC=1 SCAR=6.9
Pod documented
94  
95 return (
96 0 'Authorization' =>
97 'Bearer ' . $self->access_token
98 );
99 }
100  
101 ###########################################
102 sub token_refresh_authorization_header {
103 ###########################################
104 0 ▶ my( $self ) = @_;
Subroutine token_refresh_authorization_header: not called CC=1 SCAR=6.9
Pod undocumented
105  
106 0 return ();
107 }
108  
109 ###########################################
110 sub token_refresh {
111 ###########################################
112 0 ▶ my( $self ) = @_;
Subroutine token_refresh: not called CC=2 SCAR=17.9
Pod undocumented
113  
114 0 DEBUG "Refreshing access token";
115  
116 0 my $cache = $self->cache_read();
117  
118 0 $self->token_uri( $cache->{ token_uri } );
119  
120 my $req = &HTTP::Request::Common::POST(
121 $self->token_uri,
122 {
123 refresh_token => $cache->{ refresh_token },
124 client_id => $cache->{ client_id },
125 client_secret => $cache->{ client_secret },
126 0 grant_type => 'refresh_token',
127 },
128 $self->token_refresh_authorization_header(),
129 );
130  
131 0 my $ua = LWP::UserAgent->new();
132 0 my $resp = $ua->request($req);
133  
134 0 ▶ if( $resp->is_success() ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($resp->is_success) 0 0 0
135 0 my $data =
136 from_json( $resp->content() );
137  
138 0 DEBUG "Token refreshed, will expire in $data->{ expires_in } seconds";
139  
140 0 $cache->{ access_token } = $data->{ access_token };
141 0 $cache->{ expires } = $data->{ expires_in } + time();
142  
143 0 $self->cache_write( $cache );
144 0 return 1;
145 }
146  
147 0 ERROR "Token refresh failed: ", $resp->status_line();
148 0 return undef;
149 }
150  
151 ###########################################
152 sub token_expired {
153 ###########################################
154 0 ▶ my( $self ) = @_;
Subroutine token_expired: not called CC=3 SCAR=24.8
Pod documented
155  
156 0 my $cache = $self->cache_read();
157  
158 0 my $time_remaining = $cache->{ expires } - time();
159  
160 0 ▶ if( $time_remaining < 300 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($time_remaining < 300) 0 0 0
161 0 ▶ if( $time_remaining < 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($time_remaining < 0) { } 0 0 0
162 0 DEBUG "Token expired ", -$time_remaining, " seconds ago";
163 } else {
164 0 DEBUG "Token will expire in $time_remaining seconds";
165 }
166  
167 0 DEBUG "Token needs to be refreshed.";
168 0 return 1;
169 }
170  
171 0 return 0;
172 }
173  
174 ###########################################
175 sub token_expire {
176 ###########################################
177 0 ▶ my( $self ) = @_;
Subroutine token_expire: not called CC=1 SCAR=6.9
Pod documented
178  
179 0 my $cache = $self->cache_read();
180  
181 0 $cache->{ expires } = time() - 1;
182 0 $self->cache_write( $cache );
183 }
184  
185 ###########################################
186 sub cache_read {
187 ###########################################
188 0 ▶ my( $self ) = @_;
Subroutine cache_read: not called CC=2 SCAR=17.9
Pod undocumented
189  
190 0 ▶ if( ! -f $self->cache_file_path ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $self->cache_file_path) 0 0 0
191 0 LOGDIE "Cache file ", $self->cache_file_path, " not found. ",
192 "See GETTING STARTED in the docs for how to get started.";
193 }
194  
195 0 return LoadFile $self->cache_file_path;
196 }
197  
198 ###########################################
199 sub cache_write {
200 ###########################################
201 0 ▶ my( $self, $cache ) = @_;
Subroutine cache_write: not called CC=1 SCAR=6.9
Pod undocumented
202  
203 0 my $old_umask = umask 0177;
204  
205 0 DumpFile $self->cache_file_path, $cache;
206  
207 0 umask $old_umask;
208 0 return 1;
209 }
210  
211 ###########################################
212 sub tokens_get {
213 ###########################################
214 0 ▶ my( $self, $code ) = @_;
Subroutine tokens_get: not called CC=2 SCAR=17.9
Pod undocumented
215  
216 0 my $req = &HTTP::Request::Common::POST(
217 $self->token_uri,
218 [
219 code => $code,
220 client_id => $self->client_id,
221 client_secret => $self->client_secret,
222 redirect_uri => $self->redirect_uri,
223 grant_type => 'authorization_code',
224 ]
225 );
226  
227 0 my $ua = LWP::UserAgent->new();
228 0 my $resp = $ua->request($req);
229  
230 0 ▶ if( $resp->is_success() ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($resp->is_success) 0 0 0
231 0 my $json = $resp->content();
232 0 DEBUG "Received: [$json]",
233 my $data = from_json( $json );
234  
235 return ( $data->{ access_token },
236 $data->{ refresh_token },
237 0 $data->{ expires_in } );
238 }
239  
240 0 LOGDIE $resp->status_line();
241 0 return undef;
242 }
243  
244 ###########################################
245 sub tokens_collect {
246 ###########################################
247 0 ▶ my( $self, $code ) = @_;
Subroutine tokens_collect: not called CC=1 SCAR=6.9
Pod undocumented
248  
249 0 my( $access_token, $refresh_token,
250 $expires_in ) = $self->tokens_get( $code );
251  
252 0 my $cache = {
253 access_token => $access_token,
254 refresh_token => $refresh_token,
255 client_id => $self->client_id,
256 client_secret => $self->client_secret,
257 expires => time() + $expires_in,
258 token_uri => $self->token_uri,
259 };
260  
261 0 $self->cache_write( $cache );
262 }
263  
264 ###########################################
265 sub http_get {
266 ###########################################
267 0 ▶ my( $self, $url, $query ) = @_;
Subroutine http_get: not called CC=4 SCAR=30.0
Pod undocumented
268  
269 0 my $ua = LWP::UserAgent->new();
270  
271 0 my $uri = URI->new( $url );
272 0 ▶ $uri->query_form( @$query ) if defined $query;
Branch: 1 branch
BranchTrueFalseTotal
if defined $query 0 0 0
273  
274 0 my $resp = $ua->get( $uri,
275 $self->authorization_headers, @$query );
276  
277 0 ▶ if( $resp->is_error ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($resp->is_error) 0 0 0
278 0 ▶ if( $self->raise_error ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->raise_error) 0 0 0
279 0 die $resp->message;
280 }
281 0 return undef;
282 }
283  
284 0 return $resp->decoded_content;
285 }
286  
287 ###########################################
288 sub client_init_conf_check {
289 ###########################################
290 0 ▶ my( $self, $url ) = @_;
Subroutine client_init_conf_check: not called CC=4 SCAR=30.0
Pod undocumented
291  
292 0 my $conf = { };
293 0 ▶ if( -f $self->cache_file_path ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $self->cache_file_path) 0 0 0
294 0 $conf = $self->cache_read();
295 }
296  
297 0 ▶ if( !exists $conf->{ client_id } or
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $conf->{"client_id"} and exists $conf->{"client_secret"}) 0 0 0
Condition0%0/3
exists $conf->{"client_id"} and exists $conf->{"client_secret"}
!ll&&!rl&&r
000
MC/DC0%0/2
exists $conf->{"client_id"} and exists $conf->{"client_secret"}
exists $conf->{"client_id"} exists $conf->{"client_secret"}
Truth table0%0/3
A and B
A= exists $conf->{"client_id"}B= exists $conf->{"client_secret"}
ABresult
0X0
100
111
298 !exists $conf->{ client_secret } ) {
299 0 die "You need to register your application on " .
300 "$url and add the client_id and " .
301 "client_secret entries to " . $self->cache_file_path . "\n";
302 }
303
304 0 $self->client_id( $conf->{ client_id } );
305 0 $self->client_secret( $conf->{ client_secret } );
306  
307 0 return 1;
308 }
309  
310 1 1;
311  
312 __END__
313  
314 =head1 NAME
315  
316 OAuth::Cmdline - OAuth2 for command line applications using web services
317  
318 =head1 SYNOPSIS
319  
320 # Use a site-specific class instead of the parent class, see
321 # description below for generic cases
322  
323 my $oauth = OAuth::Cmdline::GoogleDrive->new( );
324 $oauth->access_token();
325  
326 =head1 DESCRIPTION
327  
328 OAuth::Cmdline helps standalone command line scripts to deal with
329 web services requiring OAuth access tokens.
330  
331 =head1 WARNING: LIMITED ALPHA RELEASE
332  
333 While C<OAuth::Cmdline> has been envisioned to work with
334 various OAuth-controlled web services, it is currently tested with the
335 following services, shown below with their subclasses:
336  
337 =over
338  
339 =item B<OAuth::Cmdline::GoogleDrive>
340 - Google Drive
341  
342 =item B<OAuth::Cmdline::Spotify>
343 - Spotify
344  
345 =item B<OAuth::CmdLine::MicrosoftOnline>
346 - Azure AD and other OAuth2-authenticated services that use the Microsoft
347 Online common authentication endpoint (tested with Azure AD via the Graph
348 API)
349  
350 =item B<OAuth::Cmdline::Automatic>
351 - Automatic.com car plugin
352  
353 =item B<OAuth::Cmdline::Youtube>
354 - Youtube viewer reports
355  
356 =back
357  
358 But stay tuned, I'll refactor the site-specific parts of the
359 code soon, so that it'll work with Evernote, Tumblr and others as
360 well. Hey, or send me a pull request if you want to beat me to it! :)
361  
362 If you want to use this module for a different service, go ahead and try
363 it, it might just as well work. In this case, specify the C<site> parameter,
364 which determines the name of the cache file with the access token and
365 other settings in your home directory:
366  
367 # Will use standard OAuth techniques and save your
368 # tokens in ~/.some-other.site.yml
369 my $oauth = OAuth::Cmdline->new( site => "some-other-site" );
370  
371 =head1 GETTING STARTED
372  
373 To obtain the initial set of access and refresh tokens from the
374 OAuth-controlled site, you need to register your command line app
375 with the site and you'll get a "Client ID" and a "Client Secret"
376 in return. Also, the site's SDK will point out the "Login URI" and
377 the "Token URI" to be used with the particular service.
378 Then, run the following script (the example uses the Spotify web service)
379  
380 use OAuth::Cmdline;
381 use OAuth::Cmdline::Mojo;
382  
383 my $oauth = OAuth::Cmdline::GoogleDrive->new(
384 client_id => "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
385 client_secret => "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY",
386 login_uri => "https://accounts.google.com/o/oauth2/auth",
387 token_uri => "https://accounts.google.com/o/oauth2/token",
388 scope => "user-read-private",
389 );
390
391 my $app = OAuth::Cmdline::Mojo->new(
392 oauth => $oauth,
393 );
394
395 $app->start( 'daemon', '-l', $oauth->local_uri );
396  
397 and point a browser to the URL displayed at startup. Clicking on the
398 link displayed will take you to the OAuth-controlled site, where you need
399 to log in and allow the app access to the user data, following the flow
400 provided on the site. The site will then redirect to the web server
401 started by the script, which will receive an initial access token with
402 an expiration date and a refresh token from the site, and store it locally
403 in the cache file in your home directory (~/.sitename.yml).
404  
405 =head1 ACCESS TOKEN ACCESS
406  
407 Once the cache file has been initialized, the application can use the
408 C<access_token()> method in order to get a valid access token. If
409 C<OAuth::Cmdline> finds out that the cached access token is expired,
410 it'll automatically refresh it for you behind the scenes.
411  
412 C<OAuth::Cmdline> also offers a convenience function for providing a hash
413 with authorization headers for use with LWP::UserAgent:
414  
415 my $resp = $ua->get( $url, $oauth->authorization_headers );
416  
417 This will create an "Authorization" header based on the access token and
418 include it in the request to the web service.
419  
420 =head2 Public Methods
421  
422 =over 4
423  
424 =item C<new()>
425  
426 Instantiate a new OAuth::Cmdline::XXX object. XXX stands for the specific
427 site's implementation, and can be "GoogleDrive" or one of the other
428 subclasses listed above.
429  
430 =item C<authorization_headers()>
431  
432 Returns the HTTP header name and value the specific site requires for
433 authentication. For example, in GoogleDrive's case, the values are:
434  
435 AuthorizationBearer xxxxx.yyy
436  
437 The method is used to pass the authentication header key and value
438 to an otherwise unauthenticated web request, like
439  
440 my $resp = $ua->get( $url, $oauth->authorization_headers );
441  
442 =item C<token_expired()>
443  
444 (Internal) Check if the access token is expired and will be refreshed
445 on the next call of C<authorization_headers()>.
446  
447 =item C<token_expire()>
448  
449 Force the expiration of the access token, so that the next request
450 obtains a new one.
451  
452 =back
453  
454 =head1 LEGALESE
455  
456 Copyright 2014 by Mike Schilli, all rights reserved.
457 This program is free software, you can redistribute it and/or
458 modify it under the same terms as Perl itself.
459  
460 =head1 AUTHOR
461  
462 2014, Mike Schilli <cpan@perlmeister.com>
↑ Summary Cmdline/Automatic.pm »