dolibarr 19.0.3
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 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
45
49$uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
50//$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
51//$currentUri->setQuery('');
52$currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/github_oauthcallback.php');
53
54
60$serviceFactory = new \OAuth\ServiceFactory();
61$httpClient = new \OAuth\Common\Http\Client\CurlClient();
62// TODO Set options for proxy and timeout
63// $params=array('CURLXXX'=>value, ...)
64//$httpClient->setCurlParameters($params);
65$serviceFactory->setHttpClient($httpClient);
66
67// Dolibarr storage
68$storage = new DoliStorage($db, $conf, $keyforprovider);
69
70// Setup the credentials for the requests
71$keyforparamid = 'OAUTH_GITHUB'.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
72$keyforparamsecret = 'OAUTH_GITHUB'.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
73$credentials = new Credentials(
74 getDolGlobalString($keyforparamid),
75 getDolGlobalString($keyforparamsecret),
76 $currentUri->getAbsoluteUri()
77);
78
79$requestedpermissionsarray = array();
80if (GETPOST('state')) {
81 $requestedpermissionsarray = explode(',', GETPOST('state')); // Example: 'user'. 'state' parameter is standard to retrieve some parameters back
82}
83if ($action != 'delete' && empty($requestedpermissionsarray)) {
84 print 'Error, parameter state is not defined';
85 exit;
86}
87//var_dump($requestedpermissionsarray);exit;
88
89// Instantiate the Api service using the credentials, http client and storage mechanism for the token
90$apiService = $serviceFactory->createService('GitHub', $credentials, $storage, $requestedpermissionsarray);
91
92// access type needed to have oauth provider refreshing token
93//$apiService->setAccessType('offline');
94
95$langs->load("oauth");
96
97if (!getDolGlobalString($keyforparamid)) {
98 accessforbidden('Setup of service is not complete. Customer ID is missing');
99}
100if (!getDolGlobalString($keyforparamsecret)) {
101 accessforbidden('Setup of service is not complete. Secret key is missing');
102}
103
104
105/*
106 * Actions
107 */
108
109if ($action == 'delete') {
110 $storage->clearToken('GitHub');
111
112 setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
113
114 header('Location: '.$backtourl);
115 exit();
116}
117
118if (GETPOST('code')) { // We are coming from oauth provider page
119 // We should have
120 //$_GET=array('code' => string 'aaaaaaaaaaaaaa' (length=20), 'state' => string 'user,public_repo' (length=16))
121
122 dol_syslog("We are coming from the oauth provider page code=".dol_trunc(GETPOST('code'), 5));
123
124 // This was a callback request from service, get the token
125 try {
126 //var_dump($state);
127 //var_dump($apiService); // OAuth\OAuth2\Service\GitHub
128
129 //$token = $apiService->requestAccessToken(GETPOST('code'), $state);
130 $token = $apiService->requestAccessToken(GETPOST('code'));
131 // Github is a service that does not need state to be stored as second paramater of requestAccessToken
132
133 // Into constructor of GitHub, the call
134 // parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri)
135 // has not the ending parameter to true like the Google class constructor.
136
137 setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token
138
139 $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
140 unset($_SESSION["backtourlsavedbeforeoauthjump"]);
141
142 if (empty($backtourl)) {
143 $backtourl = DOL_URL_ROOT.'/';
144 }
145
146 header('Location: '.$backtourl);
147 exit();
148 } catch (Exception $e) {
149 print $e->getMessage();
150 }
151} else { // If entry on page with no parameter, we arrive here
152 $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
153 $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
154 $_SESSION['oauthstateanticsrf'] = $state;
155
156 // This may create record into oauth_state before the header redirect.
157 // Creation of record with state in this tables depend on the Provider used (see its constructor).
158 if (GETPOST('state')) {
159 $url = $apiService->getAuthorizationUri(array('state' => GETPOST('state')));
160 } else {
161 $url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
162 }
163
164 // we go on oauth provider authorization page
165 header('Location: '.$url);
166 exit();
167}
168
169
170/*
171 * View
172 */
173
174// No view at all, just actions
175
176$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.
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.