#!perl

use strict;
use warnings;    ## required because I can't work out how to get percritic to use my modern config

package goauth;
$goauth::VERSION = '0.10';

# ABSTRACT: CLI tool with mini http server for negotiating Google OAuth2 Authorisation access tokens that allow offline access to Google API Services on behalf of the user.


use strict;
use warnings;
use Carp;
use Mojolicious::Lite;
use Data::Dumper;
use Config::JSON;
use Tie::File;
use feature 'say';
use Net::EmptyPort qw(empty_port);

use Crypt::JWT qw(decode_jwt);

my $filename;
if ( $ARGV[0] )
{
  $filename = $ARGV[0];
}
else
{
  $filename = './gapi.json';
}

if ( -e $filename )
{
  say "File $filename exists";
  input_if_not_exists( ['gapi/client_id', 'gapi/client_secret', 'gapi/scopes'] );    ## this potentially allows mreging with a json file with data external
  ## to the app or to augment missing scope from file generated from
  ##  earlier versions of goauth from other libs
  runserver();
}
else
{
  say "JSON file '$filename' with OAUTH App Secrets and user tokens not found. Creating new file...";
  setup();
  runserver();
}

sub setup
{
  ## TODO: consider allowing the gapi.json to be either seeded or to extend the credentials.json provided by Google
  my $oauth = {};
  say "Obtain project app client_id and client_secret from http://console.developers.google.com/";
  print "client_id: ";

  $oauth->{ client_id } = _stdin() || croak( 'client_id is required and has no default' );
  print "client_secret: ";

  $oauth->{ client_secret } = _stdin() || croak( 'client secret is required and has no default' );

  print
    'scopes ( space sep list - see https://developers.google.com/identity/protocols/googlescopes ): default is - email profile https://www.googleapis.com/auth/plus.profile.emails.read '
    . "https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/contacts.readonly https://mail.google.com\n";

  $oauth->{ scopes } = _stdin();    ## no croak because empty string is allowed an will evoke defaults

  ## set default scope if empty string provided
  if ( $oauth->{ scopes } eq '' )
  {
    $oauth->{ scopes }
      = 'email profile https://www.googleapis.com/auth/plus.profile.emails.read '
      . 'https://www.googleapis.com/auth/calendar '
      . 'https://www.googleapis.com/auth/contacts.readonly https://mail.google.com';
  }

  my $tokensfile = Config::JSON->create( $filename );
  $tokensfile->set( 'gapi/client_id',     $oauth->{ client_id } );
  $tokensfile->set( 'gapi/client_secret', $oauth->{ client_secret } );
  $tokensfile->set( 'gapi/scopes',        $oauth->{ scopes } );
  say 'OAuth details  updated!';

  # Remove comment for Mojolicious::Plugin::JSONConfig compatibility
  tie my @array, 'Tie::File', $filename or croak $!;
  shift @array;
  untie @array;
  return 1;
}

sub input_if_not_exists
{
  my $fields = shift;
  my $config = Config::JSON->new( $filename );
  for my $i ( @$fields )
  {
    if ( !defined $config->get( $i ) )
    {
      print "$i: ";

      #chomp( my $val = <STDIN> );
      my $val = _stdin();
      $config->set( $i, $val );
    }
  }
  return 1;
}

sub runserver
{
  my $port = empty_port( 3000 );
  say "Starting web server. Before authorization don't forget to allow redirect_uri to http://127.0.0.1 in your Google Console Project";
  $ENV{ 'GOAUTH_TOKENSFILE' } = $filename;

  my $config = Config::JSON->new( $ENV{ 'GOAUTH_TOKENSFILE' } );


  # authorize_url and token_url can be retrieved from OAuth discovery document
  # https://github.com/marcusramberg/Mojolicious-Plugin-OAuth2/issues/52
  plugin "OAuth2" => {
    google => {
      key           => $config->get( 'gapi/client_id' ),                                    # $config->{gapi}{client_id},
      secret        => $config->get( 'gapi/client_secret' ),                                #$config->{gapi}{client_secret},
      authorize_url => 'https://accounts.google.com/o/oauth2/v2/auth?response_type=code',
      token_url     => 'https://www.googleapis.com/oauth2/v4/token'                         ## NB Google credentials.json specifies "https://www.googleapis.com/oauth2/v3/token"
    }
  };

# Marked for decomission
#  helper get_email => sub {
#    my ( $c, $access_token ) = @_;
#   my %h = ( 'Authorization' => 'Bearer ' . $access_token );
#    $c->ua->get( 'https://www.googleapis.com/auth/plus.profile.emails.read' => form => \%h )->res->json;
#  };

  helper get_new_tokens => sub {
    my ( $c, $auth_code ) = @_;
    my $hash = {};
    $hash->{ code }          = $c->param( 'code' );
    $hash->{ redirect_uri }  = $c->url_for->to_abs->to_string;
    $hash->{ client_id }     = $config->get( 'gapi/client_id' );
    $hash->{ client_secret } = $config->get( 'gapi/client_secret' );
    $hash->{ grant_type }    = 'authorization_code';
    my $tokens = $c->ua->post( 'https://www.googleapis.com/oauth2/v4/token' => form => $hash )->res->json;
    return $tokens;
  };

  get "/" => sub {
    my $c = shift;
    $c->{ config } = $config;
    my $user_data;
    my $tokens;
    app->log->info( "Will store tokens in " . $config->getFilename( $config->pathToFile ) );

    if ( $c->param( 'code' ) )    ## postback from google
    {
      app->log->info( "Authorization code was retrieved: " . $c->param( 'code' ) );
      $tokens = $c->get_new_tokens( $c->param( 'code' ) );
      app->log->info( "App got new tokens: " . Dumper $tokens);
      if ( $tokens )
      {

        if ( $tokens->{ id_token } )
        {
          # my $jwt = Mojo::JWT->new(claims => $tokens->{id_token});
          # carp "Mojo header:".Dumper $jwt->header;

          # my $keys = $c->get_all_google_jwk_keys(); # arrayref
          # my ($header, $data) = decode_jwt( token => $tokens->{id_token}, decode_header => 1, key => '' ); # exctract kid
          # carp "Decode header :".Dumper $header;

          $user_data = decode_jwt( token => $tokens->{ id_token }, kid_keys => $c->ua->get( 'https://www.googleapis.com/oauth2/v3/certs' )->res->json, );

          #carp "Decoded user data:" . Dumper $user_data;
        }


        #$user_data->{email};
        #$user_data->{family_name}
        #$user_data->{given_name}
        # $tokensfile->set('tokens/'.$user_data->{email}, $tokens->{access_token});
        $config->addToHash( 'gapi/tokens/' . $user_data->{ email }, 'access_token', $tokens->{ access_token } );

        if ( $tokens->{ refresh_token } )
        {
          $config->addToHash( 'gapi/tokens/' . $user_data->{ email }, 'refresh_token', $tokens->{ refresh_token } );
        }
        else    ## with access_type=offline set we should receive a refresh token unless user already has an active one.
        {
          ## carp('Google JWT Did not incude a refresh token - when the access token expires services will become inaccessible');
        }
      }

      #$c->render( json => $config->get( 'gapi' ) );
      $c->{ access_token } = $tokens->{ access_token };
      $c->{ user_email }   = $user_data->{ email };
      $c->render( template => 'oauth_granted' );
    }
    else        ## PRESENT USER DEFAULT PAGE TO REQUEST GOOGLE AUTH'D ACCESS TO SERVICES
    {
      $c->render( template => 'oauth' );
    }
  };
  app->secrets( ['putyourownsecretcookieseedhereforsecurity' . time] );    ## NB persistence cookies not required beyond server run
  app->start( 'daemon', '-l', "http://*:$port" );
  return 1;
}

## replacement for STDIN as per https://coderwall.com/p/l9-uvq/reading-from-stdin-the-good-way
sub _stdin
{
  my $io;
  my $string = q{};

  $io = IO::Handle->new();
  if ( $io->fdopen( fileno( STDIN ), 'r' ) )
  {
    $string = $io->getline();
    $io->close();
  }
  chomp $string;
  return $string;
}

=pod

=encoding UTF-8

=head1 NAME

goauth - CLI tool with mini http server for negotiating Google OAuth2 Authorisation access tokens that allow offline access to Google API Services on behalf of the user.

=head1 VERSION

version 0.10

=head2 SUMMARY

Supports multiple users
OAuth2 for Google. You can find the key (CLIENT ID) and secret (CLIENT SECRET) from the app console here under "APIs & Auth" and "Credentials" in the menu at https://console.developers.google.com/project.

# See also https://developers.google.com/+/quickstart/.

=head2 QUICK START

Simply run from the command line

    goauth

Optionally you can provide an alternate filename to the default gapi.json as a parameter.

    goauth my_differently_named_gapi.json 

Once installed as part of the WebService::GoogleAPI::Client bundle, this tool can be run from the command line to configure a Google Project to access a Project
configuration that allows authenticated and authorised users to grant permission to access Google API services on their data (Email, Files etc) to the extent
provided by the Access Scopes for the project and the auth tokens.

In order to successfully run _go_auth_ for the first time requires the following Google Project configuration variables:
Client ID
Client Secret
List of Scopes to request access to on behalf of users ( must be a subset of those enabled for the project. )

If not already available in the gapi.json file, you will be prompted to supply these as the file is created.

Once this configuration is complete, the go_auth tool will launch a  mini HTTP server to provide an interface to request users to authorise your project application.

NB: To run successfully your Google Project must be configured to accept requests from the domain. For initial testing ensure that you include localhost in your allowed domains.

Once you have succesfully created a gapi.json file and ahve authenticated a user that is represented in this file then use WebServices::Google::Client
to start making Google API Requests.

    perldoc WebServices::Google::Client for more detail.

=head2 gapi.json 

The ultimate output of this is the gapi.json file that contains both the Google Project Specification as well as the authorised user access tokens.
The file describes a set of scopes that must all be configured as available to the Project through the Google Admin Console.
You may have multiple gapi.json files for the same project containing a different subset of scopes.
The gapi.json file also contains the authorisation tokens granted by users. Multiple users can be described within a single gapi.json file.
If users exist across multiple gapi.json files for the same project then (I believe) only the most recently granted set of scopes will be usable.

The user can revoke permissions granted to a project ( Application ) by visiting https://myaccount.google.com/permissions

This file can be used to access Google API Services using the WebServices::Google::Client Google API Client Library.

=head2 References

* probably originally based on https://gist.github.com/throughnothing/3726907

=head2 TODO: Improve user interface of the HTML templates beneath DATA section

=over 1

=item More Testing and documentation - explore cases where refresh token is not returned because previous token was issued

=item Describe alternative User Agent approaches to WebServices::Google::Client

=item Explore service accounts and possible inclusion into gapi.json

=back

=head1 AUTHOR

Peter Scott <localshop@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2017-2018 by Pavel Serikov, Peter Scott and others.

This is free software, licensed under:

  The Apache License, Version 2.0, January 2004

=cut

__DATA__

@@ oauth.html.ep

<h2>goauth Mini HTTP Server to acquire Google Authentication Tokens from a User </h2>
<br>

<%= link_to $c->oauth2->auth_url("google",
    authorize_query => { access_type => 'offline'},
		scope => $c->{config}->get('gapi/scopes'), 
		 ) =>  begin %>
<img src="data:image/png;base64,[encoded data, 10668 characters]">
<% end %>
<br>
<h2>Scopes</h2>
<ul>
  <% for my $j (split /\s/, $c->{config}->get('gapi/scopes')  ) { %>
    <li>
      <%= $j %>
    </li>
  <% } %>
</ul>


@@ oauth_granted.html.ep
<h2><%= $c->{user_email}; %> is now authenticated and has provided offline access to Google for the specified scopes</h2>
You can read more about authorization scopes in <a href="https://developers.google.com/+/web/api/rest/oauth#authorization-scopes">
the Google Developers Site</a><br/>
With this access token now saved into gapi.json you can query the available scopes etc with curl using the following command:
<br/><br/>
<span style="  background-color:#EEEEEE; font-family:Consolas,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New;">
curl <a href="https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=<%= $c->{ access_token } %>">https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=<%= $c->{ access_token } %></a>
</span>
<br/>
You can check ( and if necessary revoke ) any previously granted permissions for your user account at <a href="https://myaccount.google.com/permissions">https://myaccount.google.com/permissions</a>.





__END__




