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