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