dolibarr 25.0.0-alpha
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';
35require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php';
45use OAuth\Common\Storage\DoliStorage;
46use OAuth\Common\Consumer\Credentials;
47
48// Define $urlwithroot
49$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
50$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
51
52
53$action = GETPOST('action', 'aZ09');
54$backtourl = GETPOST('backtourl', 'alpha');
55$keyforprovider = GETPOST('keyforprovider', 'aZ09');
56if (empty($keyforprovider) && !empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) && (GETPOST('code') || $action == 'delete')) {
57 $keyforprovider = $_SESSION["oauthkeyforproviderbeforeoauthjump"];
58}
59$genericstring = 'MICROSOFT3';
60
61
65$uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
66
67
68$currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/microsoft3_oauthcallback.php');
69
70
76$serviceFactory = new \OAuth\ServiceFactory();
77$httpClient = new \OAuth\Common\Http\Client\CurlClient();
78
79$serviceFactory->setHttpClient($httpClient);
80
81// Setup the credentials for the requests
82$keyforparamid = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
83$keyforparamsecret = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
84$keyforparamtenant = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_TENANT';
85
86// Dolibarr storage
87$storage = new DoliStorage($db, $conf, $keyforprovider, getDolGlobalString($keyforparamtenant));
88
89$credentials = new Credentials(
90 getDolGlobalString($keyforparamid),
91 getDolGlobalString($keyforparamsecret),
92 $currentUri->getAbsoluteUri()
93);
94
95$state = GETPOST('state');
96
97$requestedpermissionsarray = array();
98if ($state) {
99 $requestedpermissionsarray = explode(',', $state); // Example: 'user'. 'state' parameter is standard to retrieve some parameters back
100}
101if ($action != 'delete' && empty($requestedpermissionsarray)) {
102 $langs->load("oauth");
103 print $langs->trans("OAuthErrorNoScopeInState", 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_SCOPE');
104 print '<br>'.dol_escape_htmltag(getOauthSetupDiagnostic($genericstring, $keyforprovider));
105 exit;
106}
107
108try {
109 $nameofservice = ucfirst(strtolower($genericstring));
110 $apiService = $serviceFactory->createService($nameofservice, $credentials, $storage, $requestedpermissionsarray);
111 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService'; // createService is only ServiceInterface
112} catch (Exception $e) {
113 print $e->getMessage();
114 exit;
115}
116
117if (empty($apiService)) {
118 print 'Error, failed to create serviceFactory';
119 exit;
120}
121
122$langs->load("oauth");
123
124if (!getDolGlobalString($keyforparamid)) {
125 accessforbidden('Setup of service is not complete. Customer ID is missing ('.$keyforparamid.')');
126}
127if (!getDolGlobalString($keyforparamsecret)) {
128 accessforbidden('Setup of service is not complete. Secret key is missing ('.$keyforparamsecret.')');
129}
130if (!getDolGlobalString($keyforparamtenant)) {
131 accessforbidden('Setup of service is not complete. Tenant/Annuary ID key is missing ('.$keyforparamtenant.')');
132}
133
134/*
135 * Actions
136 */
137
138if ($action == 'delete' && (!empty($user->admin) || $user->id == GETPOSTINT('userid'))) {
139 $storage->userid = GETPOSTINT('userid');
140 $storage->clearToken($genericstring);
141
142 setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
143
144 if (empty($backtourl)) {
145 $backtourl = DOL_URL_ROOT.'/';
146 }
147
148 header('Location: '.$backtourl);
149 exit();
150}
151
152
153if (GETPOST('code') || GETPOST('error')) { // We are coming from oauth provider page
154 // We should have
155
156 dol_syslog(basename(__FILE__)." We are coming from the oauth provider page code=".dol_trunc(GETPOST('code'), 5)." error=".GETPOST('error'));
157
158 // We must validate that the $state is the same than the one into $_SESSION['oauthstateanticsrf'], return error if not.
159 if (isset($_SESSION['oauthstateanticsrf']) && $state != $_SESSION['oauthstateanticsrf']) {
160 print $langs->trans("OAuthErrorStateDiffers", dol_escape_htmltag($state));
161 unset($_SESSION['oauthstateanticsrf']);
162 exit;
163 }
164
165 // This was a callback request from service, get the token
166 try {
167 if (GETPOST('error')) {
168 setEventMessages(GETPOST('error').' '.GETPOST('error_description'), null, 'errors');
169 } else {
170 $token = $apiService->requestAccessToken(GETPOST('code'));
171 setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token
172 }
173
174 $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
175 unset($_SESSION["backtourlsavedbeforeoauthjump"]);
176
177 header('Location: '.$backtourl);
178 exit();
179 } catch (Exception $e) {
180 $diag = getOauthSetupDiagnostic($genericstring, $keyforprovider);
181 dol_syslog(basename(__FILE__).' requestAccessToken failed: '.$e->getMessage().' - '.$diag, LOG_ERR);
182 print $langs->trans("OAuthErrorTokenRequestFailed", dol_escape_htmltag($e->getMessage()));
183 print '<br>'.dol_escape_htmltag($diag);
184 }
185} else {
186 // If we enter this page without 'code' parameter, we arrive here. This is the case when we want to get the redirect
187 // to the OAuth provider login page.
188 $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
189 $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
190 $_SESSION['oauthstateanticsrf'] = $state;
191
192 // This may create record into oauth_state before the header redirect.
193 // Creation of record with state in this tables depend on the Provider used (see its constructor).
194 $params = array('prompt' => 'consent');
195 if ($state) {
196 $params['state'] = $state;
197 }
198 $url = $apiService->getAuthorizationUri($params);
199
200 // Show url to get authorization
201 dol_syslog("Redirect to url=".$url);
202
203 // we go on oauth provider authorization page
204 header('Location: '.$url);
205 exit();
206}
207
208/*
209 * View
210 */
211
212// No view at all, just actions
213
214$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.