Debug Direct print module using the OAuth setup.

This commit is contained in:
Laurent Destailleur 2015-11-06 01:33:49 +01:00
parent 80ec28f9c0
commit 2dc644da30
9 changed files with 122 additions and 76 deletions

View File

@ -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 '<input type="hidden" name="action" value="update">';
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").'<br><br>';
print '<table class="noborder" width="100%">';
@ -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 '<tr class="liste_titre">';
// Api Name
$label = $langs->trans($key[0]);
print '<td colspan="2">'.$label.'</td></tr>';
if (in_array($key[0], array('OAUTH_GOOGLE_NAME')))
if ($supported)
{
$redirect_uri=$urlwithroot.'/core/modules/oauth/getgoogleoauthcallback.php';
$var = !$var;

View File

@ -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);

View File

@ -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;

View File

@ -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='<a href="'.DOL_URL_ROOT.'/admin/modules.php">'.$langs->trans("BackToModuleList").'</a>';
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='<a href="'.DOL_URL_ROOT.'/admin/modules.php">'.$langs->trans("BackToModuleList").'</a>';
//print load_fiche_titre($langs->trans("OAuthSetup"),$linkback,'title_setup');
$linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php">'.$langs->trans("BackToModuleList").'</a>';
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 '<table>';
// 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 '<tr><td>'.$langs->trans('OldTokenStored').'</td><td></td></tr>';
// print '<tr><td><pre>'.print_r($token,true).'</pre></td></tr>';
//}
//$refreshtoken = $token->getRefreshToken();
//print '<table>';
// 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 '<pre>'.print_r($apiService,true).'</pre>';
// 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 '<tr><td>'.$langs->trans('NewTokenStored').'</td><td></td></tr>';
print '<tr><td><pre>'.print_r($token,true).'</pre></td></tr>';
}
//print '<td><pre>'.print_r($token,true).'</pre></td>';
//$apiService->refreshAccessToken($token);
//print '<pre>'.print_r($apiService,true).'</pre>';
//$token = $storage->retrieveAccessToken('Google');
//print '<td><pre>'.print_r($token,true).'</pre></td>';
print '<td><a href="https://security.google.com/settings/security/permissions" target="_blank">Applications associées à votre compte</a></td>';
print '</table>';
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();

View File

@ -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');

View File

@ -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

View File

@ -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

View File

@ -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.
GoogleAuthConfigured=Google OAuth credentials found into setup of module OAuth.

View File

@ -137,7 +137,8 @@ if ($mode == 'setup' && $user->admin)
$classname = 'printing_'.$driver;
$langs->load($driver);
$printer = new $classname($db);
//print '<pre>'.print_r($printer, true).'</pre>';
//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 '<tr '.$bc[$var].'>';
print '<td>'.$langs->trans($key['varname']).'</td>';
print '<td class="button"><a href="'.$key['link'].'">'.$langs->trans('RequestAccess').'</a></td>';
print '<td><a class="button" href="'.$key['link'].'">'.$langs->trans('RequestAccess').'</a></td>';
print '<td>&nbsp;</td>';
print '</tr>'."\n";
break;
case "delete":
print '<tr '.$bc[$var].'>';
print '<td>'.$langs->trans($key['varname']).'</td>';
print '<td class="button"><a href="'.$key['link'].'">'.$langs->trans('DeleteAccess').'</a></td>';
print '<td><a class="button" href="'.$key['link'].'">'.$langs->trans('DeleteAccess').'</a></td>';
print '<td>&nbsp;</td>';
print '</tr>'."\n";
break;