Skip to content

Commit

Permalink
GH #288 #264
Browse files Browse the repository at this point in the history
  • Loading branch information
Ars92 committed Sep 5, 2023
1 parent 7ae3a63 commit 56571d5
Show file tree
Hide file tree
Showing 6 changed files with 73 additions and 176 deletions.
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,6 @@ WORDPRESS_TITLE='XCloner Testing'
WORDPRESS_ADMIN_USER=admin
WORDPRESS_ADMIN_PASSWORD=admin
WORDPRESS_ADMIN_EMAIL=[email protected]

XCLONER_GDRIVE_CLIENT_ID:
XCLONER_GDRIVE_REDIRECT_URL:
3 changes: 3 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
name: xcloner-testing

services:
wordpress:
depends_on:
Expand All @@ -21,6 +22,8 @@ services:
WORDPRESS_ADMIN_USER: "${WORDPRESS_ADMIN_USER:-admin}"
WORDPRESS_ADMIN_PASSWORD: "${WORDPRESS_ADMIN_PASSWORD:-password}"
WORDPRESS_ADMIN_EMAIL: "${WORDPRESS_ADMIN_EMAIL:[email protected]}"
XCLONER_GDRIVE_CLIENT_ID: "${XCLONER_GDRIVE_CLIENT_ID:-}"
XCLONER_GDRIVE_REDIRECT_URL: "${XCLONER_GDRIVE_REDIRECT_URL:-}"

db:
image: mariadb:10.5.8
Expand Down
2 changes: 1 addition & 1 deletion xcloner-backup-and-restore/admin/class-xcloner-admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ public function xcloner_remote_storage_page()
if (isset($_POST['authentification_code']) && $_POST['authentification_code'] != "") {
$_POST['authentification_code'] = $xcloner_sanitization->sanitize_input_as_string($_POST['authentification_code']);

$remote_storage->set_access_token($_POST['authentification_code']);
$remote_storage->gdrive_set_access_token($_POST['authentification_code']);
}

if (isset($_POST['connection_check']) && $_POST['connection_check']) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@

$gdrive_auth_url = "";

if (method_exists($remote_storage, "get_gdrive_auth_url")) {
$gdrive_auth_url = $remote_storage->get_gdrive_auth_url();
if (method_exists($remote_storage, "gdrive_get_auth_url")) {
$gdrive_auth_url = $remote_storage->gdrive_get_auth_url();
}

$gdrive_construct = $remote_storage->gdrive_construct();
Expand Down Expand Up @@ -39,12 +39,7 @@
</div>
<div class=" col s12 m9">
<p>
<?php echo sprintf(__('Click the Google Sign-in button below to complete the 1-time integration. If you would like to create your own custom app, please visit %s to create a new application and get your Client ID and Client Secret and enter it below. ', 'xcloner-backup-and-restore'), '<a href="https://console.developers.google.com" target="_blank">https://console.developers.google.com</a>') ?>
<a href="https://youtu.be/kBxf-39F4Nw" target="_blank" class="btn-floating tooltipped btn-small"
data-position="right" data-delay="50" data-html="true"
data-tooltip="<?php echo sprintf(__('Click here to view a short video explaining how to create the Client ID and Client Secret as well as connecting XCloner with the Google Drive API %s', 'xcloner-backup-and-restore'), "<br />https://youtu.be/kBxf-39F4Nw") ?>"
data-tooltip-id="92c95730-94e9-7b59-bd52-14adc30d5e3e"><i
class="material-icons">help_outline</i></a>
<?php echo sprintf(__('Click the Google Sign-in button below to complete the 1-time integration.')); ?>
</p>
</div>
</div>
Expand All @@ -65,30 +60,6 @@ class="material-icons">help_outline</i></a>
</div>
</div>

<div class="row">
<div class="col s12 m3 label">
<label for="gdrive_client_id"><?php echo __("Client ID", 'xcloner-backup-and-restore') ?></label>
</div>
<div class=" col s12 m6">
<input
placeholder="<?php echo __("Leave blank unless you wish to set up Google Drive integration manually", 'xcloner-backup-and-restore') ?>"
id="gdrive_client_id" type="text" name="xcloner_gdrive_client_id" class="validate"
value="<?php echo esc_attr(get_option("xcloner_gdrive_client_id")) ?>"
default-client-id=<?php echo $remote_storage::GDRIVE_AUTH_WATCHFUL?>>
</div>
</div>

<div class="row" id="gdrive_client_secret_wrapper">
<div class="col s12 m3 label">
<label for="gdrive_client_secret"><?php echo __("Client Secret", 'xcloner-backup-and-restore') ?></label>
</div>
<div class=" col s12 m6">
<input placeholder="<?php echo __("Google Client Secret", 'xcloner-backup-and-restore') ?>"
id="gdrive_client_secret" type="text" name="xcloner_gdrive_client_secret" class="validate"
value="<?php echo esc_attr(str_repeat('*', strlen(get_option("xcloner_gdrive_client_secret")))) ?>">
</div>
</div>

<div class="row">
<div class="col s12 m3 label">
<label for="gdrive_target_folder"><?php echo __("Folder ID or Root Path", 'xcloner-backup-and-restore') ?>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,11 +155,6 @@ function checkEndpoint() {

jQuery(document).ready(function () {

//var remote_storage = new Xcloner_Remote_Storage();

var watchful_gdrive_redirect_uri = "<?php echo $remote_storage::GDRIVE_REDIRECT_URL_WATCHFUL?>";
var default_gdrive_redirect_uri = "<?php echo $remote_storage::GDRIVE_REDIRECT_URL?>";

checkEndpoint()
jQuery("#aws_region").on("change", function () {
checkEndpoint();
Expand All @@ -175,42 +170,6 @@ function checkEndpoint() {
window.location.hash = "#" + tag;
})

if (!jQuery("#gdrive_client_id").val()) {
jQuery("#gdrive_client_secret_wrapper").hide();
}

jQuery("#gdrive_client_id").on('keyup', function () {

if (jQuery("#gdrive_client_id").val()) {
jQuery("#gdrive_client_secret_wrapper").show();
} else {
jQuery("#gdrive_client_secret_wrapper").hide();
}

})

jQuery("#gdrive_authorization_click").on("click", function (e) {

var href = (jQuery(this).attr("href"))

var client_id = jQuery("#gdrive_client_id").val() || jQuery("#gdrive_client_id").attr(
'default-client-id')

var redirect_uri = default_gdrive_redirect_uri;

if (client_id === jQuery("#gdrive_client_id").attr('default-client-id')) {
redirect_uri = watchful_gdrive_redirect_uri
}

var new_href = href.
replace(/(client_id=).*?(&)/, '$1' + client_id + '$2').
replace(/(redirect_uri=).*?(&)/, '$1' + redirect_uri + '$2');

console.log(new_href)
jQuery(this).attr("href", new_href)

});

if (location.hash) {
jQuery(location.hash).addClass("active");
}
Expand Down
165 changes: 63 additions & 102 deletions xcloner-backup-and-restore/lib/Xcloner_Remote_Storage.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,10 @@
*/
class Xcloner_Remote_Storage
{
const GDRIVE_APP_NAME = "XCloner Backup and Restore";
const GDRIVE_REDIRECT_URL = "urn:ietf:wg:oauth:2.0:oob";
const GDRIVE_REDIRECT_URL_WATCHFUL = "https://oauth.xcloner.com/google-drive/";
const GDRIVE_AUTH_WATCHFUL = "899538417626-5v4t611i8m99315nrslhu061cm1va0e6.apps.googleusercontent.com";
const DEFAULT_GDRIVE_APP_NAME = "XCloner Backup and Restore";
const DEFAULT_GDRIVE_REDIRECT_URL_WATCHFUL = "https://oauth.xcloner.com/google-drive/";
const DEFAULT_GDRIVE_CLIENT_ID = "899538417626-5v4t611i8m99315nrslhu061cm1va0e6.apps.googleusercontent.com";
const DEFAULT_GDRIVE_CLIENT_ID_V2 = "797860151656-8l7of8pkrt87q27q7g3ef0re750ls3er.apps.googleusercontent.com";

private $storage_fields = array(
"option_prefix" => "xcloner_",
Expand Down Expand Up @@ -188,8 +188,6 @@ class Xcloner_Remote_Storage
"text" => "Google Drive",
"gdrive_enable" => "int",
"gdrive_access_code" => "string",
"gdrive_client_id" => "string",
"gdrive_client_secret" => "raw",
"gdrive_target_folder" => "string",
"gdrive_cleanup_retention_limit_days" => "float",
"gdrive_empty_trash" => "int",
Expand Down Expand Up @@ -733,98 +731,56 @@ public function get_onedrive_filesystem()
return [$adapter, $filesystem];
}


public function gdrive_construct()
{
if (!class_exists('Google_Client')) {
return false;
}

$client_id = $this->xcloner_settings->get_xcloner_option('xcloner_gdrive_client_id');
$client_secret = $this->xcloner_settings->get_xcloner_option('xcloner_gdrive_client_secret');

$client = new \Google_Client();
$client->setApplicationName(self::GDRIVE_APP_NAME);
$client->setClientId(empty($client_id) ? self::GDRIVE_AUTH_WATCHFUL : $client_id);
$client->setClientSecret($client_secret);

$gdrive_redirect_url = empty($client_id) ? $this::GDRIVE_REDIRECT_URL_WATCHFUL : self::GDRIVE_REDIRECT_URL;

//$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']."?page=xcloner_remote_storage_page&action=set_gdrive_code";
$client->setApplicationName(self::DEFAULT_GDRIVE_APP_NAME);
$client->setClientId($this->gdrive_get_client_id());

$client->setRedirectUri($gdrive_redirect_url);
$client->setRedirectUri($this->gdrive_get_redirect_url());
$client->addScope('https://www.googleapis.com/auth/drive');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');

return $client;
}

public function get_gdrive_auth_url()
private function gdrive_get_client_id()
{
$client = $this->gdrive_construct();

if (!$client) {
return false;
if (!empty(getenv('XCLONER_GDRIVE_CLIENT_ID'))) {
return getenv('XCLONER_GDRIVE_CLIENT_ID');
}

return $client->createAuthUrl();
return self::DEFAULT_GDRIVE_CLIENT_ID;
}

public function gdrive_app_fetch_access_token($code, $param = "gdrive_auth_code")
private function gdrive_get_redirect_url()
{
$client = new Client([
// Base URI is used with relative requests
//'base_uri' => $this->gdrive_redirect_url,
// You can set any number of default request options.
'timeout' => 2.0,
//'headers' => [ 'Content-Type' => 'application/json' ],
//'debug' => true
]);

$response = $client->request(
'POST',
$this::GDRIVE_REDIRECT_URL_WATCHFUL,
[
'form_params' => [
$param => $code
]
]
);

$token = json_decode($response->getBody()->getContents(), true);

if ($response->getStatusCode() == 200 && $token['access_token']) {
update_option("xcloner_gdrive_access_token", json_encode($token));
} else {
$this->xcloner->trigger_message(
"%s connection error: Failed to get the AUTH code (" . $token['error'] . ")",
"error"
);
if (!empty(getenv('XCLONER_GDRIVE_REDIRECT_URL'))) {
return getenv('XCLONER_GDRIVE_REDIRECT_URL');
}

return $token;
return self::DEFAULT_GDRIVE_REDIRECT_URL_WATCHFUL;
}

public function set_access_token($code)
public function gdrive_get_auth_url()
{
$client = $this->gdrive_construct();

$client->setApplicationName($this::GDRIVE_APP_NAME);

$client_id = $this->xcloner_settings->get_xcloner_option("xcloner_gdrive_client_id");
if (!$client_id) {
$client_id = $this::GDRIVE_AUTH_WATCHFUL;

return $this->gdrive_app_fetch_access_token($code);
if (!$client) {
return false;
}
$client->setClientId($client_id);

$client->setClientSecret($this->xcloner_settings->get_xcloner_option("xcloner_gdrive_client_secret"));
$client->addScope("https://www.googleapis.com/auth/drive");
return $client->createAuthUrl();
}

$client->setRedirectUri($this::GDRIVE_REDIRECT_URL);
$client->setAccessType('offline');
public function gdrive_set_access_token($code)
{
$client = $this->gdrive_construct();

if (!$client) {
$error_msg = "Could not initialize the Google Drive Class, please check that the xcloner-google-drive plugin is enabled...";
Expand All @@ -833,48 +789,52 @@ public function set_access_token($code)
return false;
}

$token = $client->fetchAccessTokenWithAuthCode($code);

$client->setAccessToken($token);
$client->setApplicationName(self::DEFAULT_GDRIVE_APP_NAME);

update_option("xcloner_gdrive_access_token", $token);
update_option("xcloner_gdrive_refresh_token", $token['refresh_token']);

return $token;
return $this->gdrive_fetch_token_with_watchful_configuration([
'gdrive_auth_code' => $code
]);
}

public function gdrive_refresh_token($client)

private function gdrive_fetch_token_with_watchful_configuration(array $form_params)
{
$client = new Client([
'timeout' => 2.0,
]);

$form_params = array_merge($form_params, [
'use_v2' => 1
]);

$response = $client->request(
'POST',
$this->gdrive_get_redirect_url(),
[
'form_params' => $form_params
]
);

$auth_token = $this->xcloner_settings->get_xcloner_option("xcloner_gdrive_access_token");
$refresh_token = $this->xcloner_settings->get_xcloner_option("xcloner_gdrive_refresh_token");
$token = json_decode($response->getBody()->getContents(), true);

if (!$refresh_token) {
$refresh_token = $auth_token['refreh_token'];
if (empty($token['access_token'])) {
$this->xcloner->trigger_message(
"%s connection error: Failed to get the AUTH code (" . $token['error'] . ")"
);
return $token;
}

if (!$this->xcloner_settings->get_xcloner_option("xcloner_gdrive_client_id")) {
$auth_token = $this->gdrive_app_fetch_access_token($auth_token, 'gdrive_auth_refresh');
} else {
$auth_token = $client->refreshToken($refresh_token);
update_option("xcloner_gdrive_access_token", $token['access_token']);

if ($auth_token['access_token']) {
update_option("xcloner_gdrive_access_token", $auth_token);
update_option("xcloner_gdrive_refresh_token", $auth_token['refresh_token']);
} else {
$this->xcloner->trigger_message(
"%s connection error: Failed to REFRESH the AUTH code - " . $auth_token['error_description'],
"error"
);
}
if (!empty($token['refresh_token'])) {
update_option("xcloner_gdrive_refresh_token", $token['refresh_token']);
}

return $auth_token;
return $token;
}

/*
* php composer.phar remove nao-pon/flysystem-google-drive
*
/**
* @throws Exception
*/
public function get_gdrive_filesystem()
{
Expand All @@ -892,15 +852,16 @@ public function get_gdrive_filesystem()
throw new Exception($error_msg);
}

$auth_token = $this->xcloner_settings->get_xcloner_option("xcloner_gdrive_access_token");
$client->setAccessToken($auth_token);
$access_token = $this->xcloner_settings->get_xcloner_option("xcloner_gdrive_access_token");
$client->setAccessToken($access_token);

//refresh token if expired
if ($client->isAccessTokenExpired()) {
$auth_token = $this->gdrive_refresh_token($client);
$access_token = $this->gdrive_fetch_token_with_watchful_configuration([
'gdrive_auth_refresh' => $this->xcloner_settings->get_xcloner_option("xcloner_gdrive_refresh_token")
]);

if ($auth_token) {
$client->setAccessToken($auth_token);
if ($access_token) {
$client->setAccessToken($access_token);
}
}

Expand Down

0 comments on commit 56571d5

Please sign in to comment.