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