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