dolibarr  x.y.z
generic_oauthcallback.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2022 Laurent Destailleur <eldy@users.sourceforge.net>
3  * Copyright (C) 2015 Frederic France <frederic.france@free.fr>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <https://www.gnu.org/licenses/>.
17  */
18 
25 // Load Dolibarr environment
26 require '../../../main.inc.php';
27 require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
28 use OAuth\Common\Storage\DoliStorage;
29 use OAuth\Common\Consumer\Credentials;
30 use OAuth\OAuth2\Service\GitHub;
31 
32 // Define $urlwithroot
33 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
34 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
35 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
36 
37 
38 $action = GETPOST('action', 'aZ09');
39 $backtourl = GETPOST('backtourl', 'alpha');
40 $keyforprovider = GETPOST('keyforprovider', 'aZ09');
41 if (empty($keyforprovider) && !empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) && (GETPOST('code') || $action == 'delete')) {
42  $keyforprovider = $_SESSION["oauthkeyforproviderbeforeoauthjump"];
43 }
44 $genericstring = 'OTHER';
45 
46 
50 $uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
51 //$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
52 //$currentUri->setQuery('');
53 $currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/generic_oauthcallback.php');
54 
55 
61 $serviceFactory = new \OAuth\ServiceFactory();
62 $httpClient = new \OAuth\Common\Http\Client\CurlClient();
63 // TODO Set options for proxy and timeout
64 // $params=array('CURLXXX'=>value, ...)
65 //$httpClient->setCurlParameters($params);
66 $serviceFactory->setHttpClient($httpClient);
67 
68 // Dolibarr storage
69 $storage = new DoliStorage($db, $conf);
70 
71 // Setup the credentials for the requests
72 $keyforparamid = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
73 $keyforparamsecret = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
74 $credentials = new Credentials(
75  getDolGlobalString($keyforparamid),
76  getDolGlobalString($keyforparamsecret),
77  $currentUri->getAbsoluteUri()
78 );
79 
80 $requestedpermissionsarray = array();
81 if (GETPOST('state')) {
82  $requestedpermissionsarray = explode(',', GETPOST('state')); // Example: 'user'. 'state' parameter is standard to retrieve some parameters back
83 }
84 if ($action != 'delete' && empty($requestedpermissionsarray)) {
85  print 'Error, parameter state is not defined';
86  exit;
87 }
88 //var_dump($requestedpermissionsarray);exit;
89 
90 // Instantiate the Api service using the credentials, http client and storage mechanism for the token
91 $apiService = $serviceFactory->createService($genericstring, $credentials, $storage, $requestedpermissionsarray);
92 
93 /*
94 var_dump($genericstring.($keyforprovider ? '-'.$keyforprovider : ''));
95 var_dump($credentials);
96 var_dump($storage);
97 var_dump($requestedpermissionsarray);
98 */
99 
100 if (empty($apiService)) {
101  print 'Error, failed to create serviceFactory';
102  exit;
103 }
104 
105 // access type needed to have oauth provider refreshing token
106 //$apiService->setAccessType('offline');
107 
108 $langs->load("oauth");
109 
110 if (!getDolGlobalString($keyforparamid)) {
111  accessforbidden('Setup of service is not complete. Customer ID is missing');
112 }
113 if (!getDolGlobalString($keyforparamsecret)) {
114  accessforbidden('Setup of service is not complete. Secret key is missing');
115 }
116 
117 
118 /*
119  * Actions
120  */
121 
122 if ($action == 'delete') {
123  $storage->clearToken($genericstring);
124 
125  setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
126 
127  header('Location: '.$backtourl);
128  exit();
129 }
130 
131 if (GETPOST('code')) { // We are coming from oauth provider page
132  // We should have
133  //$_GET=array('code' => string 'aaaaaaaaaaaaaa' (length=20), 'state' => string 'user,public_repo' (length=16))
134 
135  dol_syslog("We are coming from the oauth provider page");
136  //llxHeader('',$langs->trans("OAuthSetup"));
137 
138  //$linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
139  //print load_fiche_titre($langs->trans("OAuthSetup"),$linkback,'title_setup');
140 
141  //print dol_get_fiche_head();
142  // retrieve the CSRF state parameter
143  $state = GETPOSTISSET('state') ? GETPOST('state') : null;
144  //print '<table>';
145 
146  // This was a callback request from service, get the token
147  try {
148  //var_dump($_GET['code']);
149  //var_dump($state);
150  //var_dump($apiService); // OAuth\OAuth2\Service\GitHub
151 
152  //$token = $apiService->requestAccessToken(GETPOST('code'), $state);
153  $token = $apiService->requestAccessToken(GETPOST('code'));
154  // Github is a service that does not need state to be stored.
155  // Into constructor of GitHub, the call
156  // parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri)
157  // has not the ending parameter to true like the Google class constructor.
158 
159  setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token
160 
161  $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
162  unset($_SESSION["backtourlsavedbeforeoauthjump"]);
163 
164  header('Location: '.$backtourl);
165  exit();
166  } catch (Exception $e) {
167  print $e->getMessage();
168  }
169 } else { // If entry on page with no parameter, we arrive here
170  $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
171  $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
172  $_SESSION['oauthstateanticsrf'] = $state;
173 
174  // This may create record into oauth_state before the header redirect.
175  // Creation of record with state in this tables depend on the Provider used (see its constructor).
176  if (GETPOST('state')) {
177  $url = $apiService->getAuthorizationUri(array('state' => GETPOST('state')));
178  } else {
179  $url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
180  }
181 
182  // we go on oauth provider authorization page
183  header('Location: '.$url);
184  exit();
185 }
186 
187 
188 /*
189  * View
190  */
191 
192 // No view at all, just actions
193 
194 $db->close();
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
if(!function_exists('utf8_encode')) if(!function_exists('utf8_decode')) getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
$uriFactory
Create a new instance of the URI class with the current URI, stripping the query string.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.