dolibarr 24.0.0-beta
github_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
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/github_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// Dolibarr storage
77$storage = new DoliStorage($db, $conf, $keyforprovider);
78
79// Setup the credentials for the requests
80$keyforparamid = 'OAUTH_GITHUB'.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
81$keyforparamsecret = 'OAUTH_GITHUB'.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
82$credentials = new Credentials(
83 getDolGlobalString($keyforparamid),
84 getDolGlobalString($keyforparamsecret),
85 $currentUri->getAbsoluteUri()
86);
87
88$state = GETPOST('state');
89
90$requestedpermissionsarray = array();
91if (GETPOST('state')) {
92 $requestedpermissionsarray = explode(',', GETPOST('state')); // Example: 'user'. 'state' parameter is standard to retrieve some parameters back
93}
94if ($action != 'delete' && empty($requestedpermissionsarray)) {
95 print 'Error, parameter state is not defined';
96 exit;
97}
98//var_dump($requestedpermissionsarray);exit;
99
100// Instantiate the Api service using the credentials, http client and storage mechanism for the token
101$apiService = null;
102$nameofservice = 'GitHub';
103try {
104 //$nameofservice = ucfirst(strtolower($genericstring));
105 $apiService = $serviceFactory->createService($nameofservice, $credentials, $storage, $requestedpermissionsarray);
106 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService'; // createService is only ServiceInterface
107} catch (Exception $e) {
108 print 'Error, failed to create service for provider '.$nameofservice.($keyforprovider ? '-'.$keyforprovider : '').'. Message was: '.$e->getMessage();
109 exit;
110}
111// access type needed to have oauth provider refreshing token
112//$apiService->setAccessType('offline');
113
114$langs->load("oauth");
115
116if (!getDolGlobalString($keyforparamid)) {
117 accessforbidden('Setup of service is not complete. Customer ID is missing');
118}
119if (!getDolGlobalString($keyforparamsecret)) {
120 accessforbidden('Setup of service is not complete. Secret key is missing');
121}
122
123
124/*
125 * Actions
126 */
127
128if ($action == 'delete' && (!empty($user->admin) || $user->id == GETPOSTINT('userid'))) {
129 $storage->userid = GETPOSTINT('userid');
130 $storage->clearToken('GitHub');
131
132 setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
133
134 header('Location: '.$backtourl);
135 exit();
136}
137
138if (GETPOST('code')) { // We are coming from oauth provider page
139 // We should have
140 //$_GET=array('code' => string 'aaaaaaaaaaaaaa' (length=20), 'state' => string 'user,public_repo' (length=16))
141
142 dol_syslog(basename(__FILE__)." We are coming from the oauth provider page code=".dol_trunc(GETPOST('code'), 5));
143
144 // This was a callback request from service, get the token
145 try {
146 //var_dump($state);
147 //var_dump($apiService); // OAuth\OAuth2\Service\GitHub
148
149 //$token = $apiService->requestAccessToken(GETPOST('code'), $state);
150 $token = $apiService->requestAccessToken(GETPOST('code'));
151 // Github is a service that does not need state to be stored as second parameter of requestAccessToken
152
153 // Into constructor of GitHub, the call
154 // parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri)
155 // has not the ending parameter to true like the Google class constructor.
156
157 setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token
158
159 $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
160 unset($_SESSION["backtourlsavedbeforeoauthjump"]);
161
162 if (empty($backtourl)) {
163 $backtourl = DOL_URL_ROOT.'/';
164 }
165
166 header('Location: '.$backtourl);
167 exit();
168 } catch (Exception $e) {
169 print $e->getMessage();
170 }
171} else { // If entry on page with no parameter, we arrive here
172 $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
173 $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
174 $_SESSION['oauthstateanticsrf'] = $state;
175
176 // This may create record into oauth_state before the header redirect.
177 // Creation of record with state in this tables depend on the Provider used (see its constructor).
178 if (GETPOST('state')) {
179 $url = $apiService->getAuthorizationUri(array('state' => GETPOST('state')));
180 } else {
181 $url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
182 }
183
184 // we go on oauth provider authorization page
185 header('Location: '.$url);
186 exit();
187}
188
189
190/*
191 * View
192 */
193
194// No view at all, just actions
195
196$db->close();
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:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
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.
if(empty($keyforprovider) &&!empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) &&(GETPOST('code')|| $action=='delete')) $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.