dolibarr 25.0.0-alpha
microsoft2_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 = 'MICROSOFT2';
55
56
60$uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
61//$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
62//$currentUri->setQuery('');
63
64$currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/microsoft2_oauthcallback.php');
65
66
72$serviceFactory = new \OAuth\ServiceFactory();
73$httpClient = new \OAuth\Common\Http\Client\CurlClient();
74// TODO Set options for proxy and timeout
75// $params=array('CURLXXX'=>value, ...)
76//$httpClient->setCurlParameters($params);
77$serviceFactory->setHttpClient($httpClient);
78
79// Setup the credentials for the requests
80$keyforparamid = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
81$keyforparamsecret = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
82$keyforparamtenant = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_TENANT';
83
84// Dolibarr storage
85$storage = new DoliStorage($db, $conf, $keyforprovider, getDolGlobalString($keyforparamtenant));
86
87$credentials = new Credentials(
88 getDolGlobalString($keyforparamid),
89 getDolGlobalString($keyforparamsecret),
90 $currentUri->getAbsoluteUri()
91);
92
93
94$state = GETPOST('state');
95
96$requestedpermissionsarray = array();
97if ($state) {
98 $requestedpermissionsarray = explode(',', $state); // Example: 'user'. 'state' parameter is standard to retrieve some parameters back
99}
100if ($action != 'delete' && empty($requestedpermissionsarray)) {
101 $langs->load("oauth");
102 print $langs->trans("OAuthErrorNoScopeInState", 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_SCOPE');
103 print '<br>'.dol_escape_htmltag(getOauthSetupDiagnostic($genericstring, $keyforprovider));
104 exit;
105}
106//var_dump($requestedpermissionsarray);exit;
107
108// Instantiate the Api service using the credentials, http client and storage mechanism for the token
109// ucfirst(strtolower($genericstring)) must be the name of a class into OAuth/OAuth2/Services/Xxxx
110// $requestedpermissionsarray contains list of scopes.
111// Conversion into URL is done by Reflection on constant with name SCOPE_scope_in_uppercase
112try {
113 $nameofservice = ucfirst(strtolower($genericstring));
114 $apiService = $serviceFactory->createService($nameofservice, $credentials, $storage, $requestedpermissionsarray);
115 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService'; // createService is only ServiceInterface
116} catch (Exception $e) {
117 print $e->getMessage();
118 exit;
119}
120/*
121var_dump($genericstring.($keyforprovider ? '-'.$keyforprovider : ''));
122var_dump($credentials);
123var_dump($storage);
124var_dump($requestedpermissionsarray);
125*/
126
127if (empty($apiService)) {
128 print 'Error, failed to create serviceFactory';
129 exit;
130}
131
132// access type needed to have oauth provider refreshing token
133//$apiService->setAccessType('offline');
134
135$langs->load("oauth");
136
137if (!getDolGlobalString($keyforparamid)) {
138 accessforbidden('Setup of service is not complete. Customer ID is missing ('.$keyforparamid.')');
139}
140if (!getDolGlobalString($keyforparamsecret)) {
141 accessforbidden('Setup of service is not complete. Secret key is missing ('.$keyforparamsecret.')');
142}
143if (!getDolGlobalString($keyforparamtenant)) {
144 accessforbidden('Setup of service is not complete. Tenant/Annuary ID key is missing ('.$keyforparamtenant.')');
145}
146
147
148/*
149 * Actions
150 */
151
152if ($action == 'delete' && (!empty($user->admin) || $user->id == GETPOSTINT('userid'))) {
153 $storage->userid = GETPOSTINT('userid');
154 $storage->clearToken($genericstring);
155
156 setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
157
158 if (empty($backtourl)) {
159 $backtourl = DOL_URL_ROOT.'/';
160 }
161
162 header('Location: '.$backtourl);
163 exit();
164}
165
166//dol_syslog("GET=".join(',', $_GET));
167
168
169if (GETPOST('code') || GETPOST('error')) { // We are coming from oauth provider page
170 // We should have
171 //$_GET=array('code' => string 'aaaaaaaaaaaaaa' (length=20), 'state' => string 'user,public_repo' (length=16))
172
173 dol_syslog(basename(__FILE__)." We are coming from the oauth provider page code=".dol_trunc(GETPOST('code'), 5)." error=".GETPOST('error'));
174
175 // This was a callback request from service, get the token
176 try {
177 //var_dump($state);
178 //var_dump($apiService); // OAuth\OAuth2\Service\Microsoft
179
180 if (GETPOST('error')) {
181 setEventMessages(GETPOST('error').' '.GETPOST('error_description'), null, 'errors');
182 } else {
183 //print GETPOST('code');exit;
184
185 //$token = $apiService->requestAccessToken(GETPOST('code'), $state);
186 $token = $apiService->requestAccessToken(GETPOST('code'));
187 // Microsoft is a service that does not need state to be stored as second parameter of requestAccessToken
188
189 //print $token->getAccessToken().'<br><br>';
190 //print $token->getExtraParams()['id_token'].'<br>';
191 //print $token->getRefreshToken().'<br>';exit;
192
193 setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token
194 }
195
196 $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
197 unset($_SESSION["backtourlsavedbeforeoauthjump"]);
198
199 header('Location: '.$backtourl);
200 exit();
201 } catch (Exception $e) {
202 $diag = getOauthSetupDiagnostic($genericstring, $keyforprovider);
203 dol_syslog(basename(__FILE__).' requestAccessToken failed: '.$e->getMessage().' - '.$diag, LOG_ERR);
204 print $langs->trans("OAuthErrorTokenRequestFailed", dol_escape_htmltag($e->getMessage()));
205 print '<br>'.dol_escape_htmltag($diag);
206 }
207} else {
208 // If we enter this page without 'code' parameter, we arrive here. This is the case when we want to get the redirect
209 // to the OAuth provider login page.
210 $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
211 $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
212 $_SESSION['oauthstateanticsrf'] = $state;
213
214 //if (!preg_match('/^forlogin/', $state)) {
215 // $apiService->setApprouvalPrompt('auto');
216 //}
217
218 // This may create record into oauth_state before the header redirect.
219 // Creation of record with state in this tables depend on the Provider used (see its constructor).
220 if ($state) {
221 $url = $apiService->getAuthorizationUri(array('state' => $state));
222 } else {
223 $url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
224 }
225
226 // Show url to get authorization
227 //var_dump((string) $url);exit;
228 dol_syslog("Redirect to url=".$url);
229
230 // we go on oauth provider authorization page
231 header('Location: '.$url);
232 exit();
233}
234
235
236/*
237 * View
238 */
239
240// No view at all, just actions
241
242$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.