dolibarr  17.0.4
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." code=".dol_trunc(GETPOST('code'), 5));
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($state);
150  //var_dump($apiService); // OAuth\OAuth2\Service\Google
151 
152  // This request the token
153  // Result is stored into object managed by class DoliStorage into includes/OAuth/Common/Storage/DoliStorage.php, so into table llx_oauth_token
154  $token = $apiService->requestAccessToken(GETPOST('code'), $state);
155 
156  // Note: The extraparams has the 'id_token' than contains a lot of information about the user.
157  $extraparams = $token->getExtraParams();
158  $jwt = explode('.', $extraparams['id_token']);
159 
160  // Extract the middle part, base64 decode, then json_decode it
161  if (!empty($jwt[1])) {
162  $userinfo = json_decode(base64_decode($jwt[1]), true);
163 
164  // TODO
165  // We should make the 5 steps of validation of id_token
166  // 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.
167  // Verify that the value of the iss claim in the ID token is equal to https://accounts.google.com or accounts.google.com.
168  // Verify that the value of the aud claim in the ID token is equal to your app's client ID.
169  // Verify that the expiry time (exp claim) of the ID token has not passed.
170  // 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.
171 
172  /*
173  $useremailuniq = $userinfo['sub'];
174  $useremail = $userinfo['email'];
175  $useremailverified = $userinfo['email_verified'];
176  $username = $userinfo['name'];
177  $userfamilyname = $userinfo['family_name'];
178  $usergivenname = $userinfo['given_name'];
179  $hd = $userinfo['hd'];
180  */
181  }
182 
183  setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs');
184 
185  $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
186  unset($_SESSION["backtourlsavedbeforeoauthjump"]);
187 
188  header('Location: '.$backtourl);
189  exit();
190  } catch (Exception $e) {
191  print $e->getMessage();
192  }
193  }
194 } else {
195  // If we enter this page without 'code' parameter, we arrive here. This is the case when we want to get the redirect
196  // to the OAuth provider login page.
197  $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
198  $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
199  $_SESSION['oauthstateanticsrf'] = $state;
200 
201  if (!preg_match('/^forlogin/', $state)) {
202  $apiService->setApprouvalPrompt('force');
203  }
204 
205  // This may create record into oauth_state before the header redirect.
206  // Creation of record with state in this tables depend on the Provider used (see its constructor).
207  if ($state) {
208  $url = $apiService->getAuthorizationUri(array('state' => $state));
209  } else {
210  $url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
211  }
212 
213  // Add more param
214  $url .= '&nonce='.bin2hex(random_bytes(64/8));
215  // TODO Add param hd and/or login_hint
216  if (!preg_match('/^forlogin/', $state)) {
217  //$url .= 'hd=xxx';
218  }
219 
220  //var_dump($url);exit;
221 
222  // we go on oauth provider authorization page
223  header('Location: '.$url);
224  exit();
225 }
226 
227 
228 /*
229  * View
230  */
231 
232 // No view at all, just actions, so we never reach this line.
233 
234 $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.
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.
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.