dolibarr 25.0.0-alpha
microsoft_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-2024 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
26// Load Dolibarr environment
27require '../../../main.inc.php';
28require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
29require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php';
39use OAuth\Common\Storage\DoliStorage;
40use OAuth\Common\Consumer\Credentials;
41
42// Define $urlwithroot
43$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
44$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
45//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
46
47
48$action = GETPOST('action', 'aZ09');
49$backtourl = GETPOST('backtourl', 'alpha');
50$keyforprovider = GETPOST('keyforprovider', 'aZ09');
51if (empty($keyforprovider) && !empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) && (GETPOST('code') || $action == 'delete')) {
52 $keyforprovider = $_SESSION["oauthkeyforproviderbeforeoauthjump"];
53}
54$genericstring = 'MICROSOFT';
55
59$uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
60//$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
61//$currentUri->setQuery('');
62$currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/microsoft_oauthcallback.php');
63
64
70$serviceFactory = new \OAuth\ServiceFactory();
71$httpClient = new \OAuth\Common\Http\Client\CurlClient();
72// TODO Set options for proxy and timeout
73// $params=array('CURLXXX'=>value, ...)
74//$httpClient->setCurlParameters($params);
75$serviceFactory->setHttpClient($httpClient);
76
77// Setup the credentials for the requests
78$keyforparamid = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
79$keyforparamsecret = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
80$keyforparamtenant = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_TENANT';
81
82// Dolibarr storage
83$storage = new DoliStorage($db, $conf, $keyforprovider, getDolGlobalString($keyforparamtenant));
84
85$credentials = new Credentials(
86 getDolGlobalString($keyforparamid),
87 getDolGlobalString($keyforparamsecret),
88 $currentUri->getAbsoluteUri()
89);
90
91$state = GETPOST('state');
92
93$requestedpermissionsarray = array();
94if ($state) {
95 $requestedpermissionsarray = explode(',', $state); // Example: 'user'. 'state' parameter is standard to retrieve some parameters back
96}
97if ($action != 'delete' && empty($requestedpermissionsarray)) {
98 $langs->load("oauth");
99 print $langs->trans("OAuthErrorNoScopeInState", 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_SCOPE');
100 print '<br>'.dol_escape_htmltag(getOauthSetupDiagnostic($genericstring, $keyforprovider));
101 exit;
102}
103//var_dump($requestedpermissionsarray);exit;
104
105// Instantiate the Api service using the credentials, http client and storage mechanism for the token
106// ucfirst(strtolower($genericstring)) must be the name of a class into OAuth/OAuth2/Services/Xxxx
107// $requestedpermissionsarray contains list of scopes.
108// Conversion into URL is done by Reflection on constant with name SCOPE_scope_in_uppercase
109try {
110 $nameofservice = ucfirst(strtolower($genericstring));
111 $apiService = $serviceFactory->createService($nameofservice, $credentials, $storage, $requestedpermissionsarray);
112 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService'; // createService is only ServiceInterface
113} catch (Exception $e) {
114 print $e->getMessage();
115 exit;
116}
117/*
118var_dump($genericstring.($keyforprovider ? '-'.$keyforprovider : ''));
119var_dump($credentials);
120var_dump($storage);
121var_dump($requestedpermissionsarray);
122*/
123
124if (empty($apiService)) {
125 print 'Error, failed to create serviceFactory';
126 exit;
127}
128
129// access type needed to have oauth provider refreshing token
130//$apiService->setAccessType('offline');
131
132$langs->load("oauth");
133
134if (!getDolGlobalString($keyforparamid)) {
135 accessforbidden('Setup of service is not complete. Customer ID is missing ('.$keyforparamid.')');
136}
137if (!getDolGlobalString($keyforparamsecret)) {
138 accessforbidden('Setup of service is not complete. Secret key is missing ('.$keyforparamsecret.')');
139}
140if (!getDolGlobalString($keyforparamtenant)) {
141 accessforbidden('Setup of service is not complete. Tenant/Annuary ID key is missing ('.$keyforparamtenant.')');
142}
143
144
145/*
146 * Actions
147 */
148
149if ($action == 'delete' && (!empty($user->admin) || $user->id == GETPOSTINT('userid'))) {
150 $storage->userid = GETPOSTINT('userid');
151 $storage->clearToken($genericstring);
152
153 setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
154
155 if (empty($backtourl)) {
156 $backtourl = DOL_URL_ROOT.'/';
157 }
158
159 header('Location: '.$backtourl);
160 exit();
161}
162
163//dol_syslog("GET=".join(',', $_GET));
164
165
166if (GETPOST('code') || GETPOST('error')) { // We are coming from oauth provider page
167 // We should have
168 //$_GET=array('code' => string 'aaaaaaaaaaaaaa' (length=20), 'state' => string 'user,public_repo' (length=16))
169
170 dol_syslog(basename(__FILE__)." We are coming from the oauth provider page code=".dol_trunc(GETPOST('code'), 5)." error=".GETPOST('error'));
171
172 // This was a callback request from service, get the token
173 try {
174 //var_dump($state);
175 //var_dump($apiService); // OAuth\OAuth2\Service\Microsoft
176
177 if (GETPOST('error')) {
178 setEventMessages(GETPOST('error').' '.GETPOST('error_description'), null, 'errors');
179 } else {
180 //print GETPOST('code');exit;
181
182 //$token = $apiService->requestAccessToken(GETPOST('code'), $state);
183 $token = $apiService->requestAccessToken(GETPOST('code'));
184 // Microsoft is a service that does not need state to be stored as second parameter of requestAccessToken
185
186 //print $token->getAccessToken().'<br><br>';
187 //print $token->getExtraParams()['id_token'].'<br><br>';
188 //print $token->getRefreshToken().'<br>';exit;
189
190 setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token
191 }
192
193 $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
194 unset($_SESSION["backtourlsavedbeforeoauthjump"]);
195
196 header('Location: '.$backtourl);
197 exit();
198 } catch (Exception $e) {
199 $diag = getOauthSetupDiagnostic($genericstring, $keyforprovider);
200 dol_syslog(basename(__FILE__).' requestAccessToken failed: '.$e->getMessage().' - '.$diag, LOG_ERR);
201 print $langs->trans("OAuthErrorTokenRequestFailed", dol_escape_htmltag($e->getMessage()));
202 print '<br>'.dol_escape_htmltag($diag);
203 }
204} else {
205 // If we enter this page without 'code' parameter, we arrive here. This is the case when we want to get the redirect
206 // to the OAuth provider login page.
207 $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
208 $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
209 $_SESSION['oauthstateanticsrf'] = $state;
210
211 //if (!preg_match('/^forlogin/', $state)) {
212 // $apiService->setApprouvalPrompt('auto');
213 //}
214
215 // This may create record into oauth_state before the header redirect.
216 // Creation of record with state in this tables depend on the Provider used (see its constructor).
217 $params = array();
218 if ($state) {
219 $params['state'] = $state;
220 }
221 if (!empty($params)) {
222 $url = $apiService->getAuthorizationUri($params);
223 } else {
224 $url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
225 }
226
227 // Show url to get authorization
228 //var_dump((string) $url);exit;
229 dol_syslog("Redirect to url=".$url);
230
231 // we go on oauth provider authorization page
232 header('Location: '.$url);
233 exit();
234}
235
236
237/*
238 * View
239 */
240
241// No view at all, just actions
242
243$db->close();
global $dolibarr_main_url_root
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
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 a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
Definition html.lib.php:172
$uriFactory
Create a new instance of the URI class with the current URI, stripping the query string.
getOauthSetupDiagnostic($genericstring, $keyforprovider='')
Return a human readable diagnostic of the setup of an OAuth2 provider entry, to append to an error me...
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.