dolibarr 20.0.0
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 is used as callback for token generation of an OAUTH request.
20// This page can also be used to make the process to login and get token as described here:
21// https://developers.google.com/identity/protocols/oauth2/openid-connect#server-flow
22
29// Force keyforprovider
30$forlogin = 0;
31if (!empty($_GET['state']) && preg_match('/^forlogin-/', $_GET['state'])) {
32 $forlogin = 1;
33 $_GET['keyforprovider'] = 'Login';
34}
35
36if (!defined('NOLOGIN') && $forlogin) {
37 define("NOLOGIN", 1); // This means this output page does not require to be logged.
38}
39
40// Load Dolibarr environment
41require '../../../main.inc.php';
42require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
43use OAuth\Common\Storage\DoliStorage;
44use OAuth\Common\Consumer\Credentials;
45
46// Define $urlwithroot
47global $dolibarr_main_url_root;
48$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
49$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
50//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
51
52$langs->load("oauth");
53
54$action = GETPOST('action', 'aZ09');
55$backtourl = GETPOST('backtourl', 'alpha');
56$keyforprovider = GETPOST('keyforprovider', 'aZ09');
57if (!GETPOSTISSET('keyforprovider') && !empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) && (GETPOST('code') || $action == 'delete')) {
58 // If we are coming from the Oauth page
59 $keyforprovider = $_SESSION["oauthkeyforproviderbeforeoauthjump"];
60}
61
62
66$uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
67//$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
68//$currentUri->setQuery('');
69$currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/google_oauthcallback.php');
70
71
77$serviceFactory = new \OAuth\ServiceFactory();
78$httpClient = new \OAuth\Common\Http\Client\CurlClient();
79// TODO Set options for proxy and timeout
80// $params=array('CURLXXX'=>value, ...)
81//$httpClient->setCurlParameters($params);
82$serviceFactory->setHttpClient($httpClient);
83
84// Setup the credentials for the requests
85$keyforparamid = 'OAUTH_GOOGLE'.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
86$keyforparamsecret = 'OAUTH_GOOGLE'.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
87$credentials = new Credentials(
88 getDolGlobalString($keyforparamid),
89 getDolGlobalString($keyforparamsecret),
90 $currentUri->getAbsoluteUri()
91);
92
93$state = GETPOST('state');
94$statewithscopeonly = '';
95$statewithanticsrfonly = '';
96
97$requestedpermissionsarray = array();
98if ($state) {
99 // 'state' parameter is standard to store a hash value and can be used to retrieve some parameters back
100 $statewithscopeonly = preg_replace('/\-.*$/', '', preg_replace('/^forlogin-/', '', $state));
101 $requestedpermissionsarray = explode(',', $statewithscopeonly); // Example: 'userinfo_email,userinfo_profile,openid,email,profile,cloud_print'.
102 $statewithanticsrfonly = preg_replace('/^.*\-/', '', $state);
103}
104
105// Add a test to check that the state parameter is provided into URL when we make the first call to ask the redirect or when we receive the callback
106// but not when callback was ok and we recall the page
107if ($action != 'delete' && !GETPOSTINT('afteroauthloginreturn') && (empty($statewithscopeonly) || empty($requestedpermissionsarray))) {
108 dol_syslog("state or statewithscopeonly and/or requestedpermissionsarray are empty");
109 setEventMessages($langs->trans('ScopeUndefined'), null, 'errors');
110 if (empty($backtourl)) {
111 $backtourl = DOL_URL_ROOT.'/';
112 }
113 header('Location: '.$backtourl);
114 exit();
115}
116
117//var_dump($requestedpermissionsarray);exit;
118
119
120// Dolibarr storage
121$storage = new DoliStorage($db, $conf, $keyforprovider);
122
123// Instantiate the Api service using the credentials, http client and storage mechanism for the token
124// $requestedpermissionsarray contains list of scopes.
125// Conversion into URL is done by Reflection on constant with name SCOPE_scope_in_uppercase
126$apiService = $serviceFactory->createService('Google', $credentials, $storage, $requestedpermissionsarray);
127
128// access type needed to have oauth provider refreshing token
129// also note that a refresh token is sent only after a prompt
130$apiService->setAccessType('offline');
131
132
133if (!getDolGlobalString($keyforparamid)) {
134 accessforbidden('Setup of service '.$keyforparamid.' is not complete. Customer ID is missing');
135}
136if (!getDolGlobalString($keyforparamsecret)) {
137 accessforbidden('Setup of service '.$keyforparamid.' is not complete. Secret key is missing');
138}
139
140
141/*
142 * Actions
143 */
144
145if ($action == 'delete') {
146 $storage->clearToken('Google');
147
148 setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
149
150 header('Location: '.$backtourl);
151 exit();
152}
153
154
155if (!GETPOST('code')) {
156 dol_syslog("Page is called without the 'code' parameter defined");
157
158 // If we enter this page without 'code' parameter, it means we click on the link from login page ($forlogin is set) or from setup page and we want to get the redirect
159 // to the OAuth provider login page.
160 $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
161 $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
162 $_SESSION['oauthstateanticsrf'] = $state;
163
164 // Save more data into session
165 // No need to save more data in sessions. We have several info into $_SESSION['datafromloginform'], saved when form is posted with a click
166 // on "Login with Google" with param actionlogin=login and beforeoauthloginredirect=google, by the functions_googleoauth.php.
167
168 // Set approval_prompt. Note: A refresh token will be provided only if prompt is done.
169 if ($forlogin) {
170 $approval_prompt = getDolGlobalString('OAUTH_GOOGLE_FORCE_PROMPT_ON_LOGIN', 'auto'); // Can be 'force'
171 $apiService->setApprouvalPrompt($approval_prompt);
172 } else {
173 $apiService->setApprouvalPrompt('force');
174 }
175
176 // This may create record into oauth_state before the header redirect.
177 // Creation of record with state, create record or just update column state of table llx_oauth_token (and create/update entry in llx_oauth_state) depending on the Provider used (see its constructor).
178 if ($state) {
179 $url = $apiService->getAuthorizationUri(array('state' => $state));
180 } else {
181 $url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
182 }
183 // The redirect_uri is included into this $url
184
185 // Add more param
186 $url .= '&nonce='.bin2hex(random_bytes(64/8));
187
188 if ($forlogin) {
189 // TODO Add param hd. What is it for ?
190 //$url .= 'hd=xxx';
191
192 if (GETPOST('username')) {
193 $url .= '&login_hint='.urlencode(GETPOST('username'));
194 }
195
196 // Check that the redirect_uri that will be used is same than url of current domain
197
198 // Define $urlwithroot
199 global $dolibarr_main_url_root;
200 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
201 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
202 //$urlwithroot = DOL_MAIN_URL_ROOT; // This is to use same domain name than current
203
204 include DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
205 $currentrooturl = getRootURLFromURL(DOL_MAIN_URL_ROOT);
206 $externalrooturl = getRootURLFromURL($urlwithroot);
207
208 if ($currentrooturl != $externalrooturl) {
209 $langs->load("errors");
210 setEventMessages($langs->trans("ErrorTheUrlOfYourDolInstanceDoesNotMatchURLIntoOAuthSetup", $currentrooturl, $externalrooturl), null, 'errors');
211 $url = DOL_URL_ROOT;
212 }
213 }
214
215 //var_dump($url);exit;
216
217 // we go on oauth provider authorization page, we will then go back on this page but into the other branch of the if (!GETPOST('code'))
218 header('Location: '.$url);
219 exit();
220} else {
221 // We are coming from the return of an OAuth2 provider page.
222 dol_syslog("We are coming from the oauth provider page keyforprovider=".$keyforprovider." code=".dol_trunc(GETPOST('code'), 5));
223
224 // We must validate that the $state is the same than the one into $_SESSION['oauthstateanticsrf'], return error if not.
225 if (isset($_SESSION['oauthstateanticsrf']) && $state != $_SESSION['oauthstateanticsrf']) {
226 //var_dump($_SESSION['oauthstateanticsrf']);exit;
227 print 'Value for state='.dol_escape_htmltag($state).' differs from value in $_SESSION["oauthstateanticsrf"]. Code is refused.';
228 unset($_SESSION['oauthstateanticsrf']);
229 } else {
230 // This was a callback request from service, get the token
231 try {
232 //var_dump($state);
233 //var_dump($apiService); // OAuth\OAuth2\Service\Google
234 //dol_syslog("_GET=".var_export($_GET, true));
235
236 $errorincheck = 0;
237
238 $db->begin();
239
240 // This requests the token from the received OAuth code (call of the https://oauth2.googleapis.com/token endpoint)
241 // Result is stored into object managed by class DoliStorage into includes/OAuth/Common/Storage/DoliStorage.php and into database table llx_oauth_token
242 $token = $apiService->requestAccessToken(GETPOST('code'), $state);
243
244 // The refresh token is inside the object token if the prompt was forced only.
245 //$refreshtoken = $token->getRefreshToken();
246 //var_dump($refreshtoken);
247
248 // Note: The extraparams has the 'id_token' than contains a lot of information about the user.
249 $extraparams = $token->getExtraParams();
250 $jwt = explode('.', $extraparams['id_token']);
251
252 $username = '';
253 $useremail = '';
254
255 // Extract the middle part, base64 decode, then json_decode it
256 if (!empty($jwt[1])) {
257 $userinfo = json_decode(base64_decode($jwt[1]), true);
258
259 dol_syslog("userinfo=".var_export($userinfo, true));
260
261 $useremail = $userinfo['email'];
262
263 /*
264 $useremailverified = $userinfo['email_verified'];
265 $useremailuniq = $userinfo['sub'];
266 $username = $userinfo['name'];
267 $userfamilyname = $userinfo['family_name'];
268 $usergivenname = $userinfo['given_name'];
269 $hd = $userinfo['hd'];
270 */
271
272 // We should make the steps of validation of id_token
273
274 // Verify that the state is the one expected
275 // TODO
276
277 // 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.
278 // TODO
279
280 // Verify that email is a verified email
281 /*if (empty($userinfo['email_verified'])) {
282 setEventMessages($langs->trans('Bad value for email, email lwas not verified by Google'), null, 'errors');
283 $errorincheck++;
284 }*/
285
286 // Verify that the value of the iss claim in the ID token is equal to https://accounts.google.com or accounts.google.com.
287 if ($userinfo['iss'] != 'accounts.google.com' && $userinfo['iss'] != 'https://accounts.google.com') {
288 setEventMessages($langs->trans('Bad value for returned userinfo[iss]'), null, 'errors');
289 $errorincheck++;
290 }
291
292 // Verify that the value of the aud claim in the ID token is equal to your app's client ID.
293 if ($userinfo['aud'] != getDolGlobalString($keyforparamid)) {
294 setEventMessages($langs->trans('Bad value for returned userinfo[aud]'), null, 'errors');
295 $errorincheck++;
296 }
297
298 // Verify that the expiry time (exp claim) of the ID token has not passed.
299 if ($userinfo['exp'] <= dol_now()) {
300 setEventMessages($langs->trans('Bad value for returned userinfo[exp]. Token expired.'), null, 'errors');
301 $errorincheck++;
302 }
303
304 // 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.
305 // $userinfo['hd'] is the domain name of Gmail account.
306 // TODO
307 }
308
309 if (!$errorincheck) {
310 // If call back to url for a OAUTH2 login
311 if ($forlogin) {
312 dol_syslog("we received the login/email to log to, it is ".$useremail);
313
314 $tmparray = (empty($_SESSION['datafromloginform']) ? array() : $_SESSION['datafromloginform']);
315 $entitytosearchuser = (isset($tmparray['entity']) ? $tmparray['entity'] : -1);
316
317 // Delete the old token
318 $storage->clearToken('Google'); // Delete the token called ("Google-".$storage->keyforprovider)
319
320 $tmpuser = new User($db);
321 $res = $tmpuser->fetch(0, '', '', 0, $entitytosearchuser, $useremail, 0, 1); // Load user. Can load with email_oauth2.
322
323 if ($res > 0) {
324 $username = $tmpuser->login;
325
326 $_SESSION['googleoauth_receivedlogin'] = dol_hash($conf->file->instance_unique_id.$username, '0');
327 dol_syslog('We set $_SESSION[\'googleoauth_receivedlogin\']='.$_SESSION['googleoauth_receivedlogin']);
328 } else {
329 $errormessage = "Failed to login using Google. User with the Email '".$useremail."' was not found";
330 if ($entitytosearchuser > 0) {
331 $errormessage .= ' ('.$langs->trans("Entity").' '.$entitytosearchuser.')';
332 }
333 $_SESSION["dol_loginmesg"] = $errormessage;
334 $errorincheck++;
335
336 dol_syslog($errormessage);
337 }
338 }
339 } else {
340 // If call back to url for a OAUTH2 login
341 if ($forlogin) {
342 $_SESSION["dol_loginmesg"] = "Failed to login using Google. OAuth callback URL retrieves a token with non valid data";
343 $errorincheck++;
344 }
345 }
346
347 if (!$errorincheck) {
348 $db->commit();
349 } else {
350 $db->rollback();
351 }
352
353 $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
354 unset($_SESSION["backtourlsavedbeforeoauthjump"]);
355
356 if (empty($backtourl)) {
357 $backtourl = DOL_URL_ROOT.'/';
358 }
359
360 // If call back to this url was for a OAUTH2 login
361 if ($forlogin) {
362 // _SESSION['googleoauth_receivedlogin'] has been set to the key to validate the next test by function_googleoauth(), so we can make the redirect
363 $backtourl .= '?actionlogin=login&afteroauthloginreturn=1&mainmenu=home'.($username ? '&username='.urlencode($username) : '').'&token='.newToken();
364 if (!empty($tmparray['entity'])) {
365 $backtourl .= '&entity='.$tmparray['entity'];
366 }
367 }
368
369 dol_syslog("Redirect now on backtourl=".$backtourl);
370
371 header('Location: '.$backtourl);
372 exit();
373 } catch (Exception $e) {
374 print $e->getMessage();
375 }
376 }
377}
378
379
380/*
381 * View
382 */
383
384// No view at all, just actions, so we reach this line only on error.
385
386$db->close();
Class to manage Dolibarr users.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_now($mode='auto')
Return date for now.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getRootURLFromURL($url)
Function root url from a long url For example: https://www.abc.mydomain.com/dir/page....
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.
dol_hash($chain, $type='0', $nosalt=0)
Returns a hash (non reversible encryption) of a string.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.