dolibarr  x.y.z
google_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 
19 // This page should make the process to login and get token as described here:
20 // https://developers.google.com/identity/protocols/oauth2/openid-connect#server-flow
21 
28 // Load Dolibarr environment
29 require '../../../main.inc.php';
30 require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
31 use OAuth\Common\Storage\DoliStorage;
32 use OAuth\Common\Consumer\Credentials;
33 use OAuth\OAuth2\Service\Google;
34 
35 // Define $urlwithroot
36 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
37 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
38 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
39 
40 
41 
42 $action = GETPOST('action', 'aZ09');
43 $backtourl = GETPOST('backtourl', 'alpha');
44 $keyforprovider = GETPOST('keyforprovider', 'aZ09');
45 if (!GETPOSTISSET('keyforprovider') && !empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) && (GETPOST('code') || $action == 'delete')) {
46  // If we are coming from the Oauth page
47  $keyforprovider = $_SESSION["oauthkeyforproviderbeforeoauthjump"];
48 }
49 
50 
54 $uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
55 //$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
56 //$currentUri->setQuery('');
57 $currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/google_oauthcallback.php');
58 
59 
65 $serviceFactory = new \OAuth\ServiceFactory();
66 $httpClient = new \OAuth\Common\Http\Client\CurlClient();
67 // TODO Set options for proxy and timeout
68 // $params=array('CURLXXX'=>value, ...)
69 //$httpClient->setCurlParameters($params);
70 $serviceFactory->setHttpClient($httpClient);
71 
72 // Setup the credentials for the requests
73 $keyforparamid = 'OAUTH_GOOGLE'.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
74 $keyforparamsecret = 'OAUTH_GOOGLE'.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
75 $credentials = new Credentials(
76  getDolGlobalString($keyforparamid),
77  getDolGlobalString($keyforparamsecret),
78  $currentUri->getAbsoluteUri()
79 );
80 
81 $state = GETPOST('state');
82 $statewithscopeonly = '';
83 $statewithanticsrfonly = '';
84 
85 $requestedpermissionsarray = array();
86 if ($state) {
87  // 'state' parameter is standard to store a hash value and can be used to retrieve some parameters back
88  $statewithscopeonly = preg_replace('/\-.*$/', '', $state);
89  $requestedpermissionsarray = explode(',', $statewithscopeonly); // Example: 'userinfo_email,userinfo_profile,openid,email,profile,cloud_print'.
90  $statewithanticsrfonly = preg_replace('/^.*\-/', '', $state);
91 }
92 
93 if ($action != 'delete' && (empty($statewithscopeonly) || empty($requestedpermissionsarray))) {
94  setEventMessages($langs->trans('ScopeUndefined'), null, 'errors');
95  header('Location: '.$backtourl);
96  exit();
97 }
98 
99 //var_dump($requestedpermissionsarray);exit;
100 
101 
102 // Dolibarr storage
103 $storage = new DoliStorage($db, $conf, $keyforprovider);
104 
105 // Instantiate the Api service using the credentials, http client and storage mechanism for the token
106 // $requestedpermissionsarray contains list of scopes.
107 // Conversion into URL is done by Reflection on constant with name SCOPE_scope_in_uppercase
108 $apiService = $serviceFactory->createService('Google', $credentials, $storage, $requestedpermissionsarray);
109 
110 // access type needed to have oauth provider refreshing token
111 // also note that a refresh token is sent only after a prompt
112 $apiService->setAccessType('offline');
113 
114 
115 $langs->load("oauth");
116 
117 if (!getDolGlobalString($keyforparamid)) {
118  accessforbidden('Setup of service is not complete. Customer ID is missing');
119 }
120 if (!getDolGlobalString($keyforparamsecret)) {
121  accessforbidden('Setup of service is not complete. Secret key is missing');
122 }
123 
124 
125 /*
126  * Actions
127  */
128 
129 
130 if ($action == 'delete') {
131  $storage->clearToken('Google');
132 
133  setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
134 
135  header('Location: '.$backtourl);
136  exit();
137 }
138 
139 if (GETPOST('code')) { // We are coming from oauth provider page.
140  dol_syslog("We are coming from the oauth provider page keyforprovider=".$keyforprovider);
141 
142  // We must validate that the $state is the same than the one into $_SESSION['oauthstateanticsrf'], return error if not.
143  if (isset($_SESSION['oauthstateanticsrf']) && $state != $_SESSION['oauthstateanticsrf']) {
144  print 'Value for state = '.dol_escape_htmltag($state).' differs from value in $_SESSION["oauthstateanticsrf"]. Code is refused.';
145  unset($_SESSION['oauthstateanticsrf']);
146  } else {
147  // This was a callback request from service, get the token
148  try {
149  //var_dump($_GET['code']);
150  //var_dump($state);
151  //var_dump($apiService); // OAuth\OAuth2\Service\Google
152 
153  // This request the token
154  // Result is stored into object managed by class DoliStorage into includes/OAuth/Common/Storage/DoliStorage.php, so into table llx_oauth_token
155  $token = $apiService->requestAccessToken(GETPOST('code'), $state);
156 
157  // Note: The extraparams has the 'id_token' than contains a lot of information about the user.
158  $extraparams = $token->getExtraParams();
159  $jwt = explode('.', $extraparams['id_token']);
160 
161  // Extract the middle part, base64 decode, then json_decode it
162  if (!empty($jwt[1])) {
163  $userinfo = json_decode(base64_decode($jwt[1]), true);
164 
165  // TODO
166  // We should make the 5 steps of validation of id_token
167  // Verify that the ID token is properly signed by the issuer. Google-issued tokens are signed using one of the certificates found at the URI specified in the jwks_uri metadata value of the Discovery document.
168  // Verify that the value of the iss claim in the ID token is equal to https://accounts.google.com or accounts.google.com.
169  // Verify that the value of the aud claim in the ID token is equal to your app's client ID.
170  // Verify that the expiry time (exp claim) of the ID token has not passed.
171  // If you specified a hd parameter value in the request, verify that the ID token has a hd claim that matches an accepted G Suite hosted domain.
172 
173  /*
174  $useremailuniq = $userinfo['sub'];
175  $useremail = $userinfo['email'];
176  $useremailverified = $userinfo['email_verified'];
177  $username = $userinfo['name'];
178  $userfamilyname = $userinfo['family_name'];
179  $usergivenname = $userinfo['given_name'];
180  $hd = $userinfo['hd'];
181  */
182  }
183 
184  setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs');
185 
186  $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
187  unset($_SESSION["backtourlsavedbeforeoauthjump"]);
188 
189  header('Location: '.$backtourl);
190  exit();
191  } catch (Exception $e) {
192  print $e->getMessage();
193  }
194  }
195 } else {
196  // If we enter this page without 'code' parameter, we arrive here. this is the case when we want to get the redirect
197  // to the OAuth provider login page.
198  $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
199  $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
200  $_SESSION['oauthstateanticsrf'] = $state;
201 
202  if (!preg_match('/^forlogin/', $state)) {
203  $apiService->setApprouvalPrompt('force');
204  }
205 
206  // This may create record into oauth_state before the header redirect.
207  // Creation of record with state in this tables depend on the Provider used (see its constructor).
208  if ($state) {
209  $url = $apiService->getAuthorizationUri(array('state' => $state));
210  } else {
211  $url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
212  }
213 
214  // Add more param
215  $url .= '&nonce='.bin2hex(random_bytes(64/8));
216  // TODO Add param hd and/or login_hint
217  if (!preg_match('/^forlogin/', $state)) {
218  //$url .= 'hd=xxx';
219  }
220 
221  // we go on oauth provider authorization page
222  header('Location: '.$url);
223  exit();
224 }
225 
226 
227 /*
228  * View
229  */
230 
231 // No view at all, just actions, so we never reach this line.
232 
233 $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.
if(!GETPOSTISSET('keyforprovider') &&!empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) &&(GETPOST('code')|| $action=='delete')) $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.