dolibarr 24.0.0-beta
microsoft3_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 * Copyright (C) 2026 Vidal Nicolas <nicolas.vidal@atm-consulting.fr>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
32// Load Dolibarr environment
33require '../../../main.inc.php';
34require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
44use OAuth\Common\Storage\DoliStorage;
45use OAuth\Common\Consumer\Credentials;
46
47// Define $urlwithroot
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
51
52$action = GETPOST('action', 'aZ09');
53$backtourl = GETPOST('backtourl', 'alpha');
54$keyforprovider = GETPOST('keyforprovider', 'aZ09');
55if (empty($keyforprovider) && !empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) && (GETPOST('code') || $action == 'delete')) {
56 $keyforprovider = $_SESSION["oauthkeyforproviderbeforeoauthjump"];
57}
58$genericstring = 'MICROSOFT3';
59
60
64$uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
65
66
67$currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/microsoft3_oauthcallback.php');
68
69
75$serviceFactory = new \OAuth\ServiceFactory();
76$httpClient = new \OAuth\Common\Http\Client\CurlClient();
77
78$serviceFactory->setHttpClient($httpClient);
79
80// Setup the credentials for the requests
81$keyforparamid = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
82$keyforparamsecret = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
83$keyforparamtenant = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_TENANT';
84
85// Dolibarr storage
86$storage = new DoliStorage($db, $conf, $keyforprovider, getDolGlobalString($keyforparamtenant));
87
88$credentials = new Credentials(
89 getDolGlobalString($keyforparamid),
90 getDolGlobalString($keyforparamsecret),
91 $currentUri->getAbsoluteUri()
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 print 'Error, parameter state is not defined';
102 exit;
103}
104
105try {
106 $nameofservice = ucfirst(strtolower($genericstring));
107 $apiService = $serviceFactory->createService($nameofservice, $credentials, $storage, $requestedpermissionsarray);
108 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService'; // createService is only ServiceInterface
109} catch (Exception $e) {
110 print $e->getMessage();
111 exit;
112}
113
114if (empty($apiService)) {
115 print 'Error, failed to create serviceFactory';
116 exit;
117}
118
119$langs->load("oauth");
120
121if (!getDolGlobalString($keyforparamid)) {
122 accessforbidden('Setup of service is not complete. Customer ID is missing');
123}
124if (!getDolGlobalString($keyforparamsecret)) {
125 accessforbidden('Setup of service is not complete. Secret key is missing');
126}
127if (!getDolGlobalString($keyforparamtenant)) {
128 accessforbidden('Setup of service is not complete. Tenant/Annuary ID key is missing');
129}
130
131/*
132 * Actions
133 */
134
135if ($action == 'delete' && (!empty($user->admin) || $user->id == GETPOSTINT('userid'))) {
136 $storage->userid = GETPOSTINT('userid');
137 $storage->clearToken($genericstring);
138
139 setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
140
141 if (empty($backtourl)) {
142 $backtourl = DOL_URL_ROOT.'/';
143 }
144
145 header('Location: '.$backtourl);
146 exit();
147}
148
149
150if (GETPOST('code') || GETPOST('error')) { // We are coming from oauth provider page
151 // We should have
152
153 dol_syslog(basename(__FILE__)." We are coming from the oauth provider page code=".dol_trunc(GETPOST('code'), 5)." error=".GETPOST('error'));
154
155 // We must validate that the $state is the same than the one into $_SESSION['oauthstateanticsrf'], return error if not.
156 if (isset($_SESSION['oauthstateanticsrf']) && $state != $_SESSION['oauthstateanticsrf']) {
157 print $langs->trans("OAuthErrorStateDiffers", dol_escape_htmltag($state));
158 unset($_SESSION['oauthstateanticsrf']);
159 exit;
160 }
161
162 // This was a callback request from service, get the token
163 try {
164 if (GETPOST('error')) {
165 setEventMessages(GETPOST('error').' '.GETPOST('error_description'), null, 'errors');
166 } else {
167 $token = $apiService->requestAccessToken(GETPOST('code'));
168 setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token
169 }
170
171 $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
172 unset($_SESSION["backtourlsavedbeforeoauthjump"]);
173
174 header('Location: '.$backtourl);
175 exit();
176 } catch (Exception $e) {
177 print $e->getMessage();
178 }
179} else {
180 // If we enter this page without 'code' parameter, we arrive here. This is the case when we want to get the redirect
181 // to the OAuth provider login page.
182 $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
183 $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
184 $_SESSION['oauthstateanticsrf'] = $state;
185
186 // This may create record into oauth_state before the header redirect.
187 // Creation of record with state in this tables depend on the Provider used (see its constructor).
188 $params = array('prompt' => 'consent');
189 if ($state) {
190 $params['state'] = $state;
191 }
192 $url = $apiService->getAuthorizationUri($params);
193
194 // Show url to get authorization
195 dol_syslog("Redirect to url=".$url);
196
197 // we go on oauth provider authorization page
198 header('Location: '.$url);
199 exit();
200}
201
202/*
203 * View
204 */
205
206// No view at all, just actions
207
208$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.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
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.
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...
$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.