Cmdline.pm

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