OAuth2/SignedJWT.pm untested

filter: Statementstmt 0.0% 0 / 62 Branchbran 0.0% 0 / 2 Conditioncond 0.0% 0 / 2 MC/DCmcdc 0.0% 0 / 1 Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 90 CC 2 SCAR 8.9
CC
2
Cov
0%
_get_access_token
6.0
new
2.0
refresh
2.0
CRAP 2.4
1 package Google::API::OAuth2::SignedJWT;
2  
3 use strict;
4 use warnings;
5  
6 use HTTP::Request::Common;
7 use JSON;
8 use JSON::WebToken;
9  
10 use constant OAUTH2_TOKEN_ENDPOINT => "https://accounts.google.com/o/oauth2/token";
11 use constant OAUTH2_CLAIM_AUDIENCE => "https://accounts.google.com/o/oauth2/token";
12 use constant JWT_GRANT_TYPE => "urn:ietf:params:oauth:grant-type:jwt-bearer";
13 use constant JWT_ALGORITHIM => "RS256";
14 use constant JWT_TYP => "JWT";
15 use constant OAUTH2_TOKEN_LIFETIME_SECS => 3600;
16  
17 sub new {
18 my ($self, $args) = @_;
19  
20 # get an access token
21 my $json_response = $self->_get_access_token($args);
22  
23 # set the access token on the object instance.
24 $args->{access_token} = $json_response->{access_token};
25 $args->{token_type} = $json_response->{token_type};
26  
27 bless { %$args }, $self;
28 }
29  
30 sub _get_access_token {
31 my ($self, $args) = @_;
32  
33 # fetch private key contents.
34 my $key_contents = $self->_readfile($args->{private_key});
35  
36 my $jwt_params = {
37 iss => $args->{service_account_name},
38 scope => $args->{scopes},
39 aud => OAUTH2_CLAIM_AUDIENCE,
40 exp => time() + OAUTH2_TOKEN_LIFETIME_SECS,
41 iat => time()
42 };
43  
44 # sub is defined, push to the array
45 if(defined($args->{sub})) {
46 $jwt_params->{sub} = $args->{sub};
47 }
48
49 # encode jwt.
50 my $jwt = JSON::WebToken::encode_jwt($jwt_params, $key_contents, JWT_ALGORITHIM, {
51 typ => JWT_TYP
52 });
53  
54 # request an access token
55 my $jwt_ua = LWP::UserAgent->new;
56 my $jwt_response = $jwt_ua->request(POST OAUTH2_TOKEN_ENDPOINT, {
57 grant_type => JWT_GRANT_TYPE,
58 assertion => $jwt
59 });
60  
61 # decode JSON response.
62 my $json_response = JSON->new->utf8->decode($jwt_response->decoded_content);
63 return $json_response;
64 }
65  
66 sub refresh {
67 my ($self) = @_;
68  
69 # get access token
70 my $json_response = $self->_get_access_token($self);
71  
72 # set response on the object instance.
73 $self->{access_token} = $json_response->{access_token};
74 $self->{token_type} = $json_response->{token_type};
75 }
76  
77 sub token_type {
78 my ($self) = @_;
79 return $self->{token_type};
80 }
81  
82 sub access_token {
83 my ($self) = @_;
84 return $self->{access_token};
85 }
86  
87 sub _readfile {
88 my ($self, $file) = @_;
89  
90 open my $handler, '<', $file
91 or die "$file not found";
92 my $key_contents = join("", <$handler>);
93 close $handler;
94 return $key_contents;
95 }
96  
97 1;