-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathGoogleDriveAuthenticator.php
78 lines (72 loc) · 2.89 KB
/
GoogleDriveAuthenticator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
namespace Codepunker\GoogleDrive;
/**
* Handles CLI authentication with gDrive
* regenerates tokens and such...
*/
class GoogleDriveAuthenticator
{
const APPLICATION_NAME = 'My Access Management';
const CREDENTIALS_PATH = __DIR__ . '/credentials.json';
const CLIENT_SECRET_PATH = __DIR__ . '/secret.json';
const SCOPES = 'https://www.googleapis.com/auth/drive.file';
private $gclient;
/**
* create a google api client instance and store it as a class property
*/
public function __construct()
{
try {
$this->gclient = new \Google_Client();
$this->gclient->setApplicationName(self::APPLICATION_NAME);
$this->gclient->addScope(self::SCOPES);
$this->gclient->setAuthConfig(self::CLIENT_SECRET_PATH);
$this->gclient->setAccessType('offline');
$this->setClient();
} catch (\Exception $e) {
echo "It looks like the API access file is missing.
Create a project on Google Cloud (".\Codepunker\Cli\CliHacker::style('https://console.cloud.google.com/apis', 'red+bold').").
Make sure you select ".\Codepunker\Cli\CliHacker::style('**OTHER**', 'red+bold')." as type.
Then make sure you've ".\Codepunker\Cli\CliHacker::style('**ENABLED**', 'red+bold')." the app.
Download the client secret and client ID as json.
Then place it as ".\Codepunker\Cli\CliHacker::style('secret.json', 'yellow+bold')." in the root folder of the repo.\n";
die;
}
}
/**
* if no access token create one
* if expired refresh...
* @return void
*/
private function setClient()
{
if (!file_exists(self::CREDENTIALS_PATH)) {
$authUrl = $this->gclient->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
$tkn = $this->gclient->authenticate($authCode);
file_put_contents(self::CREDENTIALS_PATH, json_encode($tkn));
printf("Credentials saved to %s\n", self::CREDENTIALS_PATH);
}
$tkn = file_get_contents(self::CREDENTIALS_PATH);
$this->gclient->setAccessToken($tkn);
if ($this->gclient->isAccessTokenExpired()) {
$outcome = $this->gclient->refreshToken($this->gclient->getRefreshToken());
if(!empty($outcome['error'])) {
unlink(self::CREDENTIALS_PATH);
echo \Codepunker\Cli\CliHacker::style('Unable to refresh token. Re-authorize the app.', 'red+bold') . PHP_EOL;
die();
}
file_put_contents(self::CREDENTIALS_PATH, json_encode($this->gclient->getAccessToken()));
}
}
/**
* returns the authenticated Google Api Client
* @return Google_Client
*/
public function getClient() :\Google_Client
{
return $this->gclient;
}
}