dolibarr 25.0.0-alpha
microsoftapp_oauthcallback.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2026 Florian Hoedl <trainingsmagnet@gmail.com>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
28// Load Dolibarr environment
29require '../../../main.inc.php';
30require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
40use OAuth\Common\Storage\DoliStorage;
41use OAuth\Common\Consumer\Credentials;
42
43// Define $urlwithroot
44$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
45$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
46
47
48$action = GETPOST('action', 'aZ09');
49$backtourl = GETPOST('backtourl', 'alpha');
50$keyforprovider = GETPOST('keyforprovider', 'aZ09');
51$genericstring = 'MICROSOFTAPP';
52
53
57$uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
58
59
60$currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/microsoftapp_oauthcallback.php');
61
62
68$serviceFactory = new \OAuth\ServiceFactory();
69$httpClient = new \OAuth\Common\Http\Client\CurlClient();
70
71$serviceFactory->setHttpClient($httpClient);
72
73// Setup the credentials for the requests
74$keyforparamid = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
75$keyforparamsecret = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
76$keyforparamtenant = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_TENANT';
77$keyforparamscope = 'OAUTH_'.$genericstring.($keyforprovider ? '-'.$keyforprovider : '').'_SCOPE';
78
79// Dolibarr storage
80$storage = new DoliStorage($db, $conf, $keyforprovider, getDolGlobalString($keyforparamtenant));
81
82$credentials = new Credentials(
83 getDolGlobalString($keyforparamid),
84 getDolGlobalString($keyforparamsecret),
85 $currentUri->getAbsoluteUri()
86);
87
88$langs->load("oauth");
89
90if (!getDolGlobalString($keyforparamid)) {
91 accessforbidden('Setup of service is not complete. Customer ID is missing');
92}
93if (!getDolGlobalString($keyforparamsecret)) {
94 accessforbidden('Setup of service is not complete. Secret key is missing');
95}
96if (!getDolGlobalString($keyforparamtenant)) {
97 accessforbidden('Setup of service is not complete. Tenant/Annuary ID key is missing');
98}
99
100/*
101 * Actions
102 */
103
104if ($action == 'delete' && (!empty($user->admin) || $user->id == GETPOSTINT('userid'))) {
105 $storage->userid = GETPOSTINT('userid');
106 $storage->clearToken('Microsoftapp');
107
108 setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
109
110 if (empty($backtourl)) {
111 $backtourl = DOL_URL_ROOT.'/';
112 }
113
114 header('Location: '.$backtourl);
115 exit();
116}
117
118// Default action: request a new app-only access token, server to server, and store it.
119// Only an admin can do this: the token is generated from the application credentials
120// without any consent screen on the Microsoft side (admin consent was granted into Azure).
121if (empty($user->admin)) {
122 accessforbidden('Only an admin user can request an application token');
123}
124
125if (empty($backtourl)) {
126 $backtourl = DOL_URL_ROOT.'/admin/oauthlogintokens.php';
127}
128
129// Scopes are read from the setup. If none is defined, the service fallbacks to the
130// Exchange Online ".default" scope required by the client credentials grant flow.
131$requestedpermissionsarray = array();
132if (getDolGlobalString($keyforparamscope)) {
133 $requestedpermissionsarray = explode(',', getDolGlobalString($keyforparamscope));
134}
135
136try {
137 $nameofservice = ucfirst(strtolower($genericstring));
138 $apiService = $serviceFactory->createService($nameofservice, $credentials, $storage, $requestedpermissionsarray);
139
140 if (!($apiService instanceof OAuth\OAuth2\Service\Microsoftapp)) {
141 print 'Error, failed to create serviceFactory';
142 exit;
143 }
144
145 dol_syslog(basename(__FILE__)." Request app-only access token (client credentials grant flow) for service ".$nameofservice.($keyforprovider ? '-'.$keyforprovider : ''));
146
147 $apiService->requestNewAccessToken();
148
149 setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token
150} catch (Exception $e) {
151 setEventMessages($e->getMessage(), null, 'errors');
152 dol_syslog(basename(__FILE__)." Failed to get app-only access token: ".$e->getMessage(), LOG_ERR);
153}
154
155header('Location: '.$backtourl);
156exit();
157
158/*
159 * View
160 */
161
162// No view at all, just actions
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:
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.
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.
$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.