From 2dc644da30a4671936bf04a6ddd90c6bbfd99fe4 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Fri, 6 Nov 2015 01:33:49 +0100 Subject: [PATCH] Debug Direct print module using the OAuth setup. --- htdocs/admin/oauth.php | 21 ++- htdocs/core/lib/geturl.lib.php | 2 +- htdocs/core/modules/modOauth.class.php | 2 +- .../modules/oauth/getgoogleoauthcallback.php | 124 ++++++++++-------- .../modules/printing/printgcp.modules.php | 8 +- .../OAuth/Common/Storage/DoliStorage.php | 22 +++- htdocs/langs/en_US/oauth.lang | 4 + htdocs/langs/en_US/printing.lang | 8 +- htdocs/printing/admin/printing.php | 7 +- 9 files changed, 122 insertions(+), 76 deletions(-) diff --git a/htdocs/admin/oauth.php b/htdocs/admin/oauth.php index aab05bd4c56..66878753b46 100644 --- a/htdocs/admin/oauth.php +++ b/htdocs/admin/oauth.php @@ -27,6 +27,13 @@ require '../main.inc.php'; // required Class require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; + +// Define $urlwithroot +$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); +$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file +//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current + + $langs->load("admin"); $langs->load("oauth"); @@ -36,6 +43,8 @@ if (!$user->admin) $action = GETPOST('action', 'alpha'); +// Supported OAUTH +$supportedoauth2array=array('OAUTH_GOOGLE_NAME'); // API access parameters OAUTH $list = array ( array( @@ -297,11 +306,7 @@ print ''; dol_fiche_head(array(), '', '', 0, 'technic'); -// Define $urlwithroot -$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); -$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file -//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current - +print $langs->trans("ListOfSupportedOauthProviders").'

'; print ''; @@ -309,12 +314,16 @@ $var = true; foreach ($list as $key) { + $supported=0; + if (in_array($key[0], $supportedoauth2array)) $supported=1; + if (! $supported) continue; // show only supported + print ''; // Api Name $label = $langs->trans($key[0]); print ''; - if (in_array($key[0], array('OAUTH_GOOGLE_NAME'))) + if ($supported) { $redirect_uri=$urlwithroot.'/core/modules/oauth/getgoogleoauthcallback.php'; $var = !$var; diff --git a/htdocs/core/lib/geturl.lib.php b/htdocs/core/lib/geturl.lib.php index 682ddb1b1d1..83c67509dcc 100644 --- a/htdocs/core/lib/geturl.lib.php +++ b/htdocs/core/lib/geturl.lib.php @@ -101,7 +101,7 @@ function getURLContent($url,$postorget='GET',$param='',$followlocation=1,$addhea curl_setopt($ch, CURLOPT_POST, 0); // GET } - //if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled. + //if USE_PROXY constant set at begin of this method. if ($USE_PROXY) { dol_syslog("getURLContent set proxy to ".$PROXY_HOST. ":" . $PROXY_PORT." - ".$PROXY_USER. ":" . $PROXY_PASS); diff --git a/htdocs/core/modules/modOauth.class.php b/htdocs/core/modules/modOauth.class.php index c77ab6de68e..35be63a5c59 100644 --- a/htdocs/core/modules/modOauth.class.php +++ b/htdocs/core/modules/modOauth.class.php @@ -51,7 +51,7 @@ class modOauth extends DolibarrModules $this->name = preg_replace('/^mod/i','',get_class($this)); // Module description, used if translation string 'ModuleXXXDesc' not found (where XXX is value of numeric property 'numero' of module) $this->description = "Enable OAuth authentication"; - $this->version = 'development'; // 'development' or 'experimental' or 'dolibarr' or version + $this->version = 'dolibarr'; // 'development' or 'experimental' or 'dolibarr' or version $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name); // Where to store the module in setup page (0=common,1=interface,2=others,3=very specific) $this->special = 1; diff --git a/htdocs/core/modules/oauth/getgoogleoauthcallback.php b/htdocs/core/modules/oauth/getgoogleoauthcallback.php index f1e0ddd03f3..e159198314c 100644 --- a/htdocs/core/modules/oauth/getgoogleoauthcallback.php +++ b/htdocs/core/modules/oauth/getgoogleoauthcallback.php @@ -30,14 +30,25 @@ use OAuth\Common\Consumer\Credentials; use OAuth\Common\Token\TokenInterface; use OAuth\OAuth2\Service\Google; +// Define $urlwithroot +$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); +$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file +//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current + + + $action = GETPOST('action', 'alpha'); +$backtourl = GETPOST('backtourl', 'alpha'); + /** * Create a new instance of the URI class with the current URI, stripping the query string */ $uriFactory = new \OAuth\Common\Http\Uri\UriFactory(); -$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER); -$currentUri->setQuery(''); +//$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER); +//$currentUri->setQuery(''); +$currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/getgoogleoauthcallback.php'); + /** * Load the credential for the service @@ -45,8 +56,15 @@ $currentUri->setQuery(''); /** @var $serviceFactory \OAuth\ServiceFactory An OAuth service factory. */ $serviceFactory = new \OAuth\ServiceFactory(); +$httpClient = new \OAuth\Common\Http\Client\CurlClient(); +// TODO Set options for proxy and timeout +// $params=array('CURLXXX'=>value, ...) +//$httpClient->setCurlParameters($params); +$serviceFactory->setHttpClient($httpClient); + // Dolibarr storage $storage = new DoliStorage($db, $conf); + // Setup the credentials for the requests $credentials = new Credentials( $conf->global->OAUTH_GOOGLE_ID, @@ -54,6 +72,7 @@ $credentials = new Credentials( $currentUri->getAbsoluteUri() ); + // Instantiate the Api service using the credentials, http client and storage mechanism for the token /** @var $apiService Service */ // TODO remove hardcoded array @@ -61,80 +80,71 @@ $apiService = $serviceFactory->createService('Google', $credentials, $storage, a // access type needed for google refresh token $apiService->setAccessType('offline'); -if ($action == 'delete') { - // delete token - llxHeader('',$langs->trans("OAuthSetup")); - $linkback=''.$langs->trans("BackToModuleList").''; - print load_fiche_titre($langs->trans("OAuthSetup"),$linkback,'title_setup'); - dol_fiche_head(); +$langs->load("oauth"); + + +/* + * Actions + */ + + +if ($action == 'delete') +{ $storage->clearToken('Google'); - dol_fiche_end(); + + setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs'); + + header('Location: ' . $backtourl); + exit(); +} +if (! empty($_GET['code'])) // We are coming from Google oauth page +{ + //llxHeader('',$langs->trans("OAuthSetup")); -} elseif (! empty($_GET['code'])) { - llxHeader('',$langs->trans("OAuthSetup")); + //$linkback=''.$langs->trans("BackToModuleList").''; + //print load_fiche_titre($langs->trans("OAuthSetup"),$linkback,'title_setup'); - $linkback=''.$langs->trans("BackToModuleList").''; - print load_fiche_titre($langs->trans("OAuthSetup"),$linkback,'title_setup'); - - dol_fiche_head(); + //dol_fiche_head(); // retrieve the CSRF state parameter $state = isset($_GET['state']) ? $_GET['state'] : null; - print '
'.$label.'
'; - // looking for a token already stored in db - //try { - // $token = $storage->retrieveAccessToken('Google'); - // $old_token=1; - //} catch (Exception $e) { - // $old_token=0; - //} - //if ($old_token==1) { - // print ''; - // print ''; - //} - //$refreshtoken = $token->getRefreshToken(); + //print '
'.$langs->trans('OldTokenStored').'
'.print_r($token,true).'
'; // This was a callback request from service, get the token try { - $apiService->requestAccessToken($_GET['code'], $state); + //var_dump($_GET['code']); + //var_dump($state); + //var_dump($apiService); // OAuth\OAuth2\Service\Google + $token = $apiService->requestAccessToken($_GET['code'], $state); + + setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); } catch (Exception $e) { print $e->getMessage(); } - //print '
'.print_r($apiService,true).'
'; - // retrieve new token in db - try { - $token = $storage->retrieveAccessToken('Google'); - $new_token=1; - } catch (Exception $e) { - $new_token=0; - } - $newrefreshtoken = $token->getRefreshToken(); - if (empty($newrefreshtoken) && ! empty($refreshtoken)) { - $token->setRefreshToken($refreshtoken); - $storage->storeAccessToken('Google', $token); - } - if ($new_token==1) { - print ''; - print ''; - } - //print ''; - //$apiService->refreshAccessToken($token); - //print '
'.print_r($apiService,true).'
'; - //$token = $storage->retrieveAccessToken('Google'); - //print ''; - print ''; - print '
'.$langs->trans('NewTokenStored').'
'.print_r($token,true).'
'.print_r($token,true).'
'.print_r($token,true).'
Applications associées à votre compte
'; - - dol_fiche_end(); -} else { + $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"]; + unset($_SESSION["backtourlsavedbeforeoauthjump"]); + + header('Location: ' . $backtourl); + exit(); +} +else +{ + $_SESSION["backtourlsavedbeforeoauthjump"]=$backtourl; + $url = $apiService->getAuthorizationUri(); // we go on google authorization page header('Location: ' . $url); exit(); } -llxFooter(); + +/* + * View + */ + +// No view at all, just actions $db->close(); + diff --git a/htdocs/core/modules/printing/printgcp.modules.php b/htdocs/core/modules/printing/printgcp.modules.php index 7010ec7de78..aab1ae13bb6 100644 --- a/htdocs/core/modules/printing/printgcp.modules.php +++ b/htdocs/core/modules/printing/printgcp.modules.php @@ -87,6 +87,8 @@ class printing_printgcp extends PrintingDriver $this->errors[] = $e->getMessage(); $token_ok = false; } + //var_dump($this->errors);exit; + $expire = false; // Is token expired or will token expire in the next 30 seconds if ($token_ok) { @@ -116,12 +118,12 @@ class printing_printgcp extends PrintingDriver $refreshtoken = $token->getRefreshToken(); $this->conf[] = array('varname'=>'PRINTGCP_TOKEN_REFRESH', 'info'=>((! empty($refreshtoken))?'Yes':'No'), 'type'=>'info'); $this->conf[] = array('varname'=>'PRINTGCP_TOKEN_EXPIRED', 'info'=>($expire?'Yes':'No'), 'type'=>'info'); - $this->conf[] = array('varname'=>'PRINTGCP_TOKEN_EXPIRE_AT', 'info'=>(date("Y-m-d H:i:s", $token->getEndOfLife())), 'type'=>'info'); + $this->conf[] = array('varname'=>'PRINTGCP_TOKEN_EXPIRE_AT', 'info'=>(dol_print_date($token->getEndOfLife(), "dayhour")), 'type'=>'info'); } if (!$storage->hasAccessToken('Google')) { - $this->conf[] = array('varname'=>'PRINTGCP_AUTHLINK', 'link'=>$urlwithroot.'/core/modules/oauth/getgoogleoauthcallback.php', 'type'=>'authlink'); + $this->conf[] = array('varname'=>'PRINTGCP_AUTHLINK', 'link'=>$urlwithroot.'/core/modules/oauth/getgoogleoauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp'), 'type'=>'authlink'); } else { - $this->conf[] = array('varname'=>'PRINTGCP_DELETE_TOKEN', 'link'=>$urlwithroot.'/core/modules/oauth/getgoogleoauthcallback.php?action=delete', 'type'=>'delete'); + $this->conf[] = array('varname'=>'PRINTGCP_DELETE_TOKEN', 'link'=>$urlwithroot.'/core/modules/oauth/getgoogleoauthcallback.php?action=delete&backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp'), 'type'=>'delete'); } } else { $this->conf[] = array('varname'=>'PRINTGCP_INFO', 'info'=>'GoogleAuthNotConfigured', 'type'=>'info'); diff --git a/htdocs/includes/OAuth/Common/Storage/DoliStorage.php b/htdocs/includes/OAuth/Common/Storage/DoliStorage.php index 2e4b9c195a2..0ce3abf39c1 100644 --- a/htdocs/includes/OAuth/Common/Storage/DoliStorage.php +++ b/htdocs/includes/OAuth/Common/Storage/DoliStorage.php @@ -86,6 +86,10 @@ class DoliStorage implements TokenStorageInterface */ public function storeAccessToken($service, TokenInterface $token) { + //var_dump("storeAccessToken"); + //var_dump($token); + dol_syslog("storeAccessToken"); + $serializedToken = serialize($token); $this->tokens[$service] = $token; @@ -95,6 +99,10 @@ class DoliStorage implements TokenStorageInterface $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."oauth_token"; $sql.= " WHERE service='".$service."' AND entity=1"; $resql = $this->db->query($sql); + if (! $resql) + { + dol_print_error($this->db); + } $obj = $this->db->fetch_array($resql); if ($obj) { // update @@ -108,7 +116,8 @@ class DoliStorage implements TokenStorageInterface $sql.= " VALUES ('".$service."', '".$this->db->escape($serializedToken)."', 1)"; $resql = $this->db->query($sql); } - + //print $sql; + // allow chaining return $this; } @@ -122,8 +131,13 @@ class DoliStorage implements TokenStorageInterface $sql = "SELECT token FROM ".MAIN_DB_PREFIX."oauth_token"; $sql.= " WHERE service='".$service."'"; $resql = $this->db->query($sql); + if (! $resql) + { + dol_print_error($this->db); + } $result = $this->db->fetch_array($resql); - $token = unserialize($result[token]); + $token = unserialize($result['token']); + $this->tokens[$service] = $token; return is_array($this->tokens) @@ -194,6 +208,10 @@ class DoliStorage implements TokenStorageInterface $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."oauth_state"; $sql.= " WHERE service='".$service."' AND entity=1"; $resql = $this->db->query($sql); + if (! $resql) + { + dol_print_error($this->db); + } $obj = $this->db->fetch_array($resql); if ($obj) { // update diff --git a/htdocs/langs/en_US/oauth.lang b/htdocs/langs/en_US/oauth.lang index ef58d605c49..4567af2a0b6 100644 --- a/htdocs/langs/en_US/oauth.lang +++ b/htdocs/langs/en_US/oauth.lang @@ -1,7 +1,11 @@ # Dolibarr language file - Source file is en_US - oauth ConfigOAuth=Oauth Configuration NoAccessToken=No token access saved. +HasAccessToken=A token was generated and saved into database +NewTokenStored=Token received ans saved +TokenDeleted=Token deleted UseTheFollowingUrlAsRedirectURI=Use the following URL as the Redirect URI when creating your credential on your OAuth provider: +ListOfSupportedOauthProviders=Enter here credential provided by your OAuth2 provider. Only supported OAuth2 providers are visible here. This setup may be used by other modules than need OAuth2 authentication. OAUTH_AMAZON_NAME=Api Amazon OAUTH_AMAZON_ID=Api Amazon Id OAUTH_AMAZON_SECRET=Api Amazon Secret diff --git a/htdocs/langs/en_US/printing.lang b/htdocs/langs/en_US/printing.lang index a4f9fe09e04..fa154976603 100644 --- a/htdocs/langs/en_US/printing.lang +++ b/htdocs/langs/en_US/printing.lang @@ -20,11 +20,13 @@ UserConf=Setup per user PRINTGCP=Google Cloud Print PRINTGCP_INFO=Google Api State PRINTGCP_AUTHLINK=Authentication -PRINTGCP_TOKEN_ACCESS=Google Cloud Print Token +PRINTGCP_TOKEN_ACCESS=Google Cloud Print OAuth Token PRINTGCP_TOKEN_REFRESH=Token Refresh Present PRINTGCP_TOKEN_EXPIRED=Token Expired PRINTGCP_TOKEN_EXPIRE_AT=Token expire at -RequestAccess=Request Access +PRINTGCP_DELETE_TOKEN=Delete saved token +RequestAccess=Click here to request access and receive a token to save +DeleteAccess=Click here to delete token PrintGCPDesc=This driver allow to send documents directly to a printer with Google Cloud Print. PrintingDriverDescprintgcp=Configuration variables for printing driver Google Cloud Print. PrintTestDescprintgcp=List of Printers for Google Cloud Print. @@ -83,4 +85,4 @@ MEDIA_IPP_thermal=Thermal IPP_COLOR_print-black=BW Printer DirectPrintingJobsDesc=This page lists printing jobs found for available printers. GoogleAuthNotConfigured=Google OAuth setup not done. Enable module OAuth and set a Google ID/Secret. -GoogleAuthConfigured=Google OAuth credentials found. \ No newline at end of file +GoogleAuthConfigured=Google OAuth credentials found into setup of module OAuth. \ No newline at end of file diff --git a/htdocs/printing/admin/printing.php b/htdocs/printing/admin/printing.php index ac6f030ae16..ce87a5c7178 100644 --- a/htdocs/printing/admin/printing.php +++ b/htdocs/printing/admin/printing.php @@ -137,7 +137,8 @@ if ($mode == 'setup' && $user->admin) $classname = 'printing_'.$driver; $langs->load($driver); $printer = new $classname($db); - //print '
'.print_r($printer, true).'
'; + //var_dump($printer); + $i=0; $submit_enabled=0; foreach ($printer->conf as $key) @@ -157,14 +158,14 @@ if ($mode == 'setup' && $user->admin) case "authlink": print ''; print ''.$langs->trans($key['varname']).''; - print ''.$langs->trans('RequestAccess').''; + print ''.$langs->trans('RequestAccess').''; print ' '; print ''."\n"; break; case "delete": print ''; print ''.$langs->trans($key['varname']).''; - print ''.$langs->trans('DeleteAccess').''; + print ''.$langs->trans('DeleteAccess').''; print ' '; print ''."\n"; break;