Analytics/OAuth2.pm untested

filter: Statementstmt 0.0% 0 / 50 Branchbran 0.0% 0 / 10 Conditioncond 0.0% 0 / 2 MC/DCmcdc 0.0% 0 / 1 Subroutinesub 0.0% 0 / 10 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 78 CC 6 SCAR 17.2
CC
6
Cov
0%
new
12.0
authorize_url
6.0
get_access_token
6.0
CRAP 5.6
1 package Net::Google::Analytics::OAuth2;
2 $Net::Google::Analytics::OAuth2::VERSION = '3.05';
3 use strict;
4 use warnings;
5  
6 # ABSTRACT: OAuth2 for Google Analytics API
7  
8 use JSON;
9 use LWP::UserAgent;
10 use URI;
11  
12 sub new {
13 my $class = shift;
14 my $self = { @_ };
15  
16 die("client_id missing") if !$self->{client_id};
17 die("client_secret missing") if !$self->{client_secret};
18  
19 $self->{redirect_uri} ||= 'urn:ietf:wg:oauth:2.0:oob';
20  
21 return bless($self, $class);
22 }
23  
24 sub authorize_url {
25 my $self = shift;
26 my $extra_params = @_ == 1 ? $_[0] : { @_ };
27  
28 my $uri = URI->new('https://accounts.google.com/o/oauth2/auth');
29 $uri->query_form(
30 response_type => 'code',
31 client_id => $self->{client_id},
32 redirect_uri => $self->{redirect_uri},
33 scope => 'https://www.googleapis.com/auth/analytics.readonly',
34 %$extra_params,
35 );
36  
37 return $uri->as_string;
38 }
39  
40 sub get_access_token {
41 my ($self, $code) = @_;
42  
43 my $ua = LWP::UserAgent->new;
44 my $res = $ua->post('https://accounts.google.com/o/oauth2/token', [
45 code => $code,
46 client_id => $self->{client_id},
47 client_secret => $self->{client_secret},
48 redirect_uri => $self->{redirect_uri},
49 grant_type => 'authorization_code',
50 ]);
51  
52 die('error getting token: ' . $res->status_line) unless $res->is_success;
53  
54 return from_json($res->decoded_content);
55 }
56  
57 sub refresh_access_token {
58 my ($self, $refresh_token) = @_;
59  
60 my $ua = LWP::UserAgent->new;
61 my $res = $ua->post('https://accounts.google.com/o/oauth2/token', [
62 refresh_token => $refresh_token,
63 client_id => $self->{client_id},
64 client_secret => $self->{client_secret},
65 grant_type => 'refresh_token',
66 ]);
67  
68 die('error getting token: ' . $res->status_line) unless $res->is_success;
69  
70 return from_json($res->decoded_content);
71 }
72  
73 sub interactive {
74 my $self = shift;
75  
76 my $url = $self->authorize_url;
77  
78 print(<<"EOF");
79 Please visit the following URL, grant access to this application, and enter
80 the code you will be shown:
81  
82 $url
83  
84 EOF
85  
86 print("Enter code: ");
87 my $code = <STDIN>;
88 chomp($code);
89  
90 print("\nUsing code: $code\n\n");
91  
92 my $res = $self->get_access_token($code);
93  
94 print("Access token: ", $res->{access_token}, "\n");
95 print("Refresh token: ", $res->{refresh_token}, "\n");
96 }
97  
98 1;
99  
100 __END__