GoogleClientAPI
GoogleClientAPI copied to clipboard
Make getClient() hookable to change the client's authentication method.
There is a way with Google's API to use the API's services without the Ouath2 authentication, using something called service accounts.
I've built a module that overrides the getClient() method so that it's easier to just swap the client with one that is trying to authenticate using a service account json secret auth like this:
class ServiceAccountForGoogleClient extends WireData implements Module {
public static function getModuleInfo() {
return array(
'title' => 'GoogleClientAPI Service Account Hook',
'summary' => 'Provides service-account authentication for GoogleClientAPI without modifying the original module.',
'author' => 'Eduardo San Miguel',
'icon' => 'key',
'version' => 1,
'autoload' => true,
'singular' => true,
'requires' => array('ProcessWire>=3.0.0', 'GoogleClientAPI'),
);
}
public function init() {
// Hook before getClient so we can replace it entirely for service accounts
if(!(int) $this->enabled) return;
$this->addHookBefore('GoogleClientAPI::getClient', function(HookEvent $event) {
$authConfig = $this->serviceAccountJson;
if(!$authConfig) throw new WireException('Service account authentication is not configured');
$authConfig = json_decode($authConfig, true);
if((string) ($authConfig['type'] ?? '') !== 'service_account') throw new WireException('Service account authentication is not configured'); // not a service account, let original getClient() run
// Merge options similar to GoogleClientAPI::getClient
$client = new \Google_Client();
$client->setAuthConfig($authConfig);
$client->setScopes($this->scopes);
$event->return = $client; // return our client
$event->replace = true; // prevent original getClient() from running
});
}
}
Altough this solution depends on getClient() being hookable.