Net-Google-DataAPI
view release on metacpan or search on metacpan
lib/Net/Google/DataAPI/Auth/OAuth2.pm view on Meta::CPAN
package Net::Google::DataAPI::Auth::OAuth2;
use Any::Moose;
use Net::Google::DataAPI::Types;
with 'Net::Google::DataAPI::Role::Auth';
use Net::OAuth2::Client;
use Net::OAuth2::Profile::WebServer;
use HTTP::Request::Common;
our $VERSION = '0.05';
has [qw(client_id client_secret)] => (is => 'ro', isa => 'Str', required => 1);
has redirect_uri => (is => 'ro', isa => 'Str', default => 'urn:ietf:wg:oauth:2.0:oob');
has scope => (is => 'ro', isa => 'ArrayRef[Str]', required => 1, auto_deref => 1,
default => sub {[
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/userinfo.email'
]},
);
has state => (is => 'ro', isa => 'Str', default => '');
has site => (is => 'ro', isa => 'Str', default => 'https://accounts.google.com');
has authorize_path => (is => 'ro', isa => 'Str', default => '/o/oauth2/auth');
has access_token_path => (is => 'ro', isa => 'Str', default => '/o/oauth2/token');
has userinfo_url => (is => 'ro', isa => 'Str', default => 'https://www.googleapis.com/oauth2/v1/userinfo');
has oauth2_client => (is => 'ro', isa => 'Net::OAuth2::Client', required => 1, lazy_build => 1);
sub _build_oauth2_client {
my $self = shift;
Net::OAuth2::Client->new(
$self->client_id,
$self->client_secret,
site => $self->site,
authorize_path => $self->authorize_path,
access_token_path => $self->access_token_path,
refresh_token_path => $self->access_token_path,
);
}
has oauth2_webserver => (is => 'ro', isa => 'Net::OAuth2::Profile::WebServer', required => 1, lazy_build => 1);
sub _build_oauth2_webserver {
my $self = shift;
$self->oauth2_client->web_server(
redirect_uri => $self->redirect_uri,
state => $self->state,
);
}
has access_token => (is => 'rw', isa => 'Net::Google::DataAPI::Types::OAuth2::AccessToken', coerce => 1);
sub authorize_url {
my $self = shift;
return $self->oauth2_webserver->authorize(
scope => join(' ', $self->scope),
@_
);
}
sub get_access_token {
my ($self, $code) = @_;
my $token = $self->oauth2_webserver->get_access_token($code) or return;
$self->access_token($token);
}
sub refresh_token {
my ($self, $refresh_token) = @_;
$self->oauth2_webserver->update_access_token($self->access_token);
$self->access_token->refresh;
}
sub userinfo {
my $self = shift;
my $at = $self->access_token or die 'access_token is required';
my $url = URI->new($self->userinfo_url);
my $res = $at->get($url);
$res->is_success or die 'userinfo request failed: '.$res->as_string;
my %res_params = $self->oauth2_webserver->params_from_response($res)
or die 'params_from_response for userinfo response failed';
( run in 1.597 second using v1.01-cache-2.11-cpan-39bf76dae61 )