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