oauthlogintokens.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. <?php
  2. /* Copyright (C) 2013-2016 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2014-2018 Frederic France <frederic.france@netlogic.fr>
  4. * Copyright (C) 2020 Nicolas ZABOURI <info@inovea-conseil.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. /**
  20. * \file htdocs/admin/oauthlogintokens.php
  21. * \ingroup oauth
  22. * \brief Setup page to configure oauth access to login information
  23. */
  24. require '../main.inc.php';
  25. require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
  26. require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php'; // This define $list and $supportedoauth2array
  27. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  28. use OAuth\Common\Storage\DoliStorage;
  29. // Load translation files required by the page
  30. $langs->loadLangs(array('admin', 'printing', 'oauth'));
  31. $action = GETPOST('action', 'aZ09');
  32. $mode = GETPOST('mode', 'alpha');
  33. $value = GETPOST('value', 'alpha');
  34. $varname = GETPOST('varname', 'alpha');
  35. $driver = GETPOST('driver', 'alpha');
  36. if (!empty($driver)) {
  37. $langs->load($driver);
  38. }
  39. if (!$mode) {
  40. $mode = 'setup';
  41. }
  42. if (!$user->admin) {
  43. accessforbidden();
  44. }
  45. /*
  46. * Action
  47. */
  48. /*if (($mode == 'test' || $mode == 'setup') && empty($driver))
  49. {
  50. setEventMessages($langs->trans('PleaseSelectaDriverfromList'), null);
  51. header("Location: ".$_SERVER['PHP_SELF'].'?mode=config');
  52. exit;
  53. }*/
  54. if ($action == 'setconst' && $user->admin) {
  55. $error = 0;
  56. $db->begin();
  57. $setupconstarray = GETPOST('setupdriver', 'array');
  58. foreach ($setupconstarray as $setupconst) {
  59. //print '<pre>'.print_r($setupconst, true).'</pre>';
  60. $constname = dol_escape_htmltag($setupconst['varname']);
  61. $constvalue = dol_escape_htmltag($setupconst['value']);
  62. $consttype = dol_escape_htmltag($setupconst['type']);
  63. $constnote = dol_escape_htmltag($setupconst['note']);
  64. $result = dolibarr_set_const($db, $constname, $constvalue, $consttype, 0, $constnote, $conf->entity);
  65. if (!$result > 0) {
  66. $error++;
  67. }
  68. }
  69. if (!$error) {
  70. $db->commit();
  71. setEventMessages($langs->trans("SetupSaved"), null);
  72. } else {
  73. $db->rollback();
  74. dol_print_error($db);
  75. }
  76. $action = '';
  77. }
  78. if ($action == 'setvalue' && $user->admin) {
  79. $db->begin();
  80. $result = dolibarr_set_const($db, $varname, $value, 'chaine', 0, '', $conf->entity);
  81. if (!$result > 0) {
  82. $error++;
  83. }
  84. if (!$error) {
  85. $db->commit();
  86. setEventMessages($langs->trans("SetupSaved"), null);
  87. } else {
  88. $db->rollback();
  89. dol_print_error($db);
  90. }
  91. $action = '';
  92. }
  93. /*
  94. * View
  95. */
  96. // Define $urlwithroot
  97. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  98. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  99. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  100. $form = new Form($db);
  101. llxHeader('', $langs->trans("TokenManager"));
  102. $linkback = '<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
  103. print load_fiche_titre($langs->trans('ConfigOAuth'), $linkback, 'title_setup');
  104. $head = oauthadmin_prepare_head();
  105. print dol_get_fiche_head($head, 'tokengeneration', '', -1, 'technic');
  106. if (GETPOST('error')) {
  107. setEventMessages(GETPOST('error'), null, 'errors');
  108. }
  109. if ($mode == 'setup' && $user->admin) {
  110. print '<span class="opacitymedium">'.$langs->trans("OAuthSetupForLogin")."</span><br><br>\n";
  111. foreach ($list as $key) {
  112. $supported = 0;
  113. $keyforsupportedoauth2array = $key[0];
  114. if (in_array($keyforsupportedoauth2array, array_keys($supportedoauth2array))) {
  115. $supported = 1;
  116. }
  117. if (!$supported) {
  118. continue; // show only supported
  119. }
  120. $OAUTH_SERVICENAME = empty($supportedoauth2array[$keyforsupportedoauth2array]['name']) ? 'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array]['name'];
  121. // Define $shortscope, $urltorenew, $urltodelete, $urltocheckperms
  122. // TODO Use array $supportedoauth2array
  123. if ($keyforsupportedoauth2array == 'OAUTH_GITHUB_NAME') {
  124. // List of keys that will be converted into scopes (from constants 'SCOPE_state_in_uppercase' in file of service).
  125. // We pass this param list in to 'state' because we need it before and after the redirect.
  126. $shortscope = 'user,public_repo';
  127. $urltorenew = $urlwithroot.'/core/modules/oauth/github_oauthcallback.php?shortscope='.$shortscope.'&state='.$shortscope.'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
  128. $urltodelete = $urlwithroot.'/core/modules/oauth/github_oauthcallback.php?action=delete&token='.newToken().'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
  129. $urltocheckperms = 'https://github.com/settings/applications/';
  130. } elseif ($keyforsupportedoauth2array == 'OAUTH_GOOGLE_NAME') {
  131. // List of keys that will be converted into scopes (from constants 'SCOPE_state_in_uppercase' in file of service).
  132. // List of scopes for Google are here: https://developers.google.com/identity/protocols/oauth2/scopes
  133. // We pass this key list into the param 'state' because we need it before and after the redirect.
  134. $shortscope = 'userinfo_email,userinfo_profile';
  135. $shortscope .= ',openid,email,profile'; // For openid connect
  136. if (!empty($conf->printing->enabled)) {
  137. $shortscope .= ',cloud_print';
  138. }
  139. if (!empty($conf->global->OAUTH_GOOGLE_GSUITE)) {
  140. $shortscope .= ',admin_directory_user';
  141. }
  142. if (!empty($conf->global->OAUTH_GOOGLE_GMAIL)) {
  143. $shortscope.=',gmail_full';
  144. }
  145. $oauthstateanticsrf = bin2hex(random_bytes(128/8));
  146. $_SESSION['oauthstateanticsrf'] = $shortscope.'-'.$oauthstateanticsrf;
  147. $urltorenew = $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?shortscope='.$shortscope.'&state='.$shortscope.'-'.$oauthstateanticsrf.'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
  148. $urltodelete = $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&token='.newToken().'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
  149. $urltocheckperms = 'https://security.google.com/settings/security/permissions';
  150. } elseif ($keyforsupportedoauth2array == 'OAUTH_STRIPE_TEST_NAME') {
  151. $urltorenew = $urlwithroot.'/core/modules/oauth/stripetest_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
  152. $urltodelete = '';
  153. $urltocheckperms = '';
  154. } elseif ($keyforsupportedoauth2array == 'OAUTH_STRIPE_LIVE_NAME') {
  155. $urltorenew = $urlwithroot.'/core/modules/oauth/stripelive_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
  156. $urltodelete = '';
  157. $urltocheckperms = '';
  158. } else {
  159. $urltorenew = '';
  160. $urltodelete = '';
  161. $urltocheckperms = '';
  162. }
  163. // Show value of token
  164. $tokenobj = null;
  165. // Token
  166. require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
  167. require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
  168. // Dolibarr storage
  169. $storage = new DoliStorage($db, $conf);
  170. try {
  171. $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
  172. } catch (Exception $e) {
  173. // Return an error if token not found
  174. }
  175. // Set other properties
  176. $refreshtoken = false;
  177. $expiredat = '';
  178. $expire = false;
  179. // Is token expired or will token expire in the next 30 seconds
  180. if (is_object($tokenobj)) {
  181. $expire = ($tokenobj->getEndOfLife() !== $tokenobj::EOL_NEVER_EXPIRES && $tokenobj->getEndOfLife() !== $tokenobj::EOL_UNKNOWN && time() > ($tokenobj->getEndOfLife() - 30));
  182. }
  183. if ($key[1] != '' && $key[2] != '') {
  184. if (is_object($tokenobj)) {
  185. $refreshtoken = $tokenobj->getRefreshToken();
  186. $endoflife = $tokenobj->getEndOfLife();
  187. if ($endoflife == $tokenobj::EOL_NEVER_EXPIRES) {
  188. $expiredat = $langs->trans("Never");
  189. } elseif ($endoflife == $tokenobj::EOL_UNKNOWN) {
  190. $expiredat = $langs->trans("Unknown");
  191. } else {
  192. $expiredat = dol_print_date($endoflife, "dayhour");
  193. }
  194. }
  195. }
  196. $submit_enabled = 0;
  197. print '<form method="post" action="'.$_SERVER["PHP_SELF"].'?mode=setup&amp;driver='.$driver.'" autocomplete="off">';
  198. print '<input type="hidden" name="token" value="'.newToken().'">';
  199. print '<input type="hidden" name="action" value="setconst">';
  200. print '<div class="div-table-responsive-no-min">';
  201. print '<table class="noborder centpercent">'."\n";
  202. print '<tr class="liste_titre">';
  203. print '<th class="titlefieldcreate">';
  204. print img_picto('', $supportedoauth2array[$keyforsupportedoauth2array]['picto'], 'class="pictofixedwidth"');
  205. print $langs->trans($keyforsupportedoauth2array);
  206. print '</th>';
  207. print '<th></th>';
  208. print '<th></th>';
  209. print "</tr>\n";
  210. print '<tr class="oddeven">';
  211. print '<td'.($key['required'] ? ' class="required"' : '').'>';
  212. //var_dump($key);
  213. print $langs->trans("OAuthIDSecret").'</td>';
  214. print '<td>';
  215. print '<span class="opacitymedium">'.$langs->trans("SeePreviousTab").'</span>';
  216. print '</td>';
  217. print '<td>';
  218. print '</td>';
  219. print '</tr>'."\n";
  220. print '<tr class="oddeven">';
  221. print '<td'.($key['required'] ? ' class="required"' : '').'>';
  222. //var_dump($key);
  223. print $langs->trans("IsTokenGenerated");
  224. print '</td>';
  225. print '<td>';
  226. if (is_object($tokenobj)) {
  227. print $langs->trans("HasAccessToken");
  228. } else {
  229. print '<span class="opacitymedium">'.$langs->trans("NoAccessToken").'</span>';
  230. }
  231. print '</td>';
  232. print '<td width="50%">';
  233. // Links to delete/checks token
  234. if (is_object($tokenobj)) {
  235. //test on $storage->hasAccessToken($OAUTH_SERVICENAME) ?
  236. print '<a class="button smallpaddingimp" href="'.$urltodelete.'">'.$langs->trans('DeleteAccess').'</a><br>';
  237. }
  238. // Request remote token
  239. if ($urltorenew) {
  240. print '<a class="button smallpaddingimp" href="'.$urltorenew.'">'.$langs->trans('RequestAccess').'</a><br>';
  241. }
  242. // Check remote access
  243. if ($urltocheckperms) {
  244. print '<br>'.$langs->trans("ToCheckDeleteTokenOnProvider", $OAUTH_SERVICENAME).': <a href="'.$urltocheckperms.'" target="_'.strtolower($OAUTH_SERVICENAME).'">'.$urltocheckperms.'</a>';
  245. }
  246. print '</td>';
  247. print '</tr>';
  248. print '<tr class="oddeven">';
  249. print '<td'.($key['required'] ? ' class="required"' : '').'>';
  250. //var_dump($key);
  251. print $langs->trans("Token").'</td>';
  252. print '<td colspan="2">';
  253. if (is_object($tokenobj)) {
  254. //var_dump($tokenobj);
  255. print $tokenobj->getAccessToken().'<br>';
  256. //print 'Refresh: '.$tokenobj->getRefreshToken().'<br>';
  257. //print 'EndOfLife: '.$tokenobj->getEndOfLife().'<br>';
  258. //var_dump($tokenobj->getExtraParams());
  259. /*print '<br>Extra: <br><textarea class="quatrevingtpercent">';
  260. print ''.join(',',$tokenobj->getExtraParams());
  261. print '</textarea>';*/
  262. }
  263. print '</td>';
  264. print '</tr>'."\n";
  265. if (is_object($tokenobj)) {
  266. // Token refresh
  267. print '<tr class="oddeven">';
  268. print '<td'.($key['required'] ? ' class="required"' : '').'>';
  269. //var_dump($key);
  270. print $langs->trans("TOKEN_REFRESH").'</td>';
  271. print '<td colspan="2">';
  272. print yn($refreshtoken);
  273. print '</td>';
  274. print '</tr>';
  275. // Token expired
  276. print '<tr class="oddeven">';
  277. print '<td'.($key['required'] ? ' class="required"' : '').'>';
  278. //var_dump($key);
  279. print $langs->trans("TOKEN_EXPIRED").'</td>';
  280. print '<td colspan="2">';
  281. print yn($expire);
  282. print '</td>';
  283. print '</tr>';
  284. // Token expired at
  285. print '<tr class="oddeven">';
  286. print '<td'.($key['required'] ? ' class="required"' : '').'>';
  287. //var_dump($key);
  288. print $langs->trans("TOKEN_EXPIRE_AT").'</td>';
  289. print '<td colspan="2">';
  290. print $expiredat;
  291. print '</td>';
  292. print '</tr>';
  293. }
  294. print '</table>';
  295. print '</div>';
  296. if (!empty($driver)) {
  297. if ($submit_enabled) {
  298. print $form->buttonsSaveCancel("Modify", '');
  299. }
  300. }
  301. print '</form>';
  302. }
  303. }
  304. if ($mode == 'test' && $user->admin) {
  305. print $langs->trans('PrintTestDesc'.$driver)."<br><br>\n";
  306. print '<div class="div-table-responsive-no-min">';
  307. print '<table class="noborder centpercent">';
  308. if (!empty($driver)) {
  309. require_once DOL_DOCUMENT_ROOT.'/core/modules/printing/'.$driver.'.modules.php';
  310. $classname = 'printing_'.$driver;
  311. $langs->load($driver);
  312. $printer = new $classname($db);
  313. //print '<pre>'.print_r($printer, true).'</pre>';
  314. if (count($printer->getlistAvailablePrinters())) {
  315. if ($printer->listAvailablePrinters() == 0) {
  316. print $printer->resprint;
  317. } else {
  318. setEventMessages($printer->error, $printer->errors, 'errors');
  319. }
  320. } else {
  321. print $langs->trans('PleaseConfigureDriverfromList');
  322. }
  323. }
  324. print '</table>';
  325. print '</div>';
  326. }
  327. if ($mode == 'userconf' && $user->admin) {
  328. print $langs->trans('PrintUserConfDesc'.$driver)."<br><br>\n";
  329. print '<div class="div-table-responsive">';
  330. print '<table class="noborder centpercent">';
  331. print '<tr class="liste_titre">';
  332. print '<th>'.$langs->trans("User").'</th>';
  333. print '<th>'.$langs->trans("PrintModule").'</th>';
  334. print '<th>'.$langs->trans("PrintDriver").'</th>';
  335. print '<th>'.$langs->trans("Printer").'</th>';
  336. print '<th>'.$langs->trans("PrinterLocation").'</th>';
  337. print '<th>'.$langs->trans("PrinterId").'</th>';
  338. print '<th>'.$langs->trans("NumberOfCopy").'</th>';
  339. print '<th class="center">'.$langs->trans("Delete").'</th>';
  340. print "</tr>\n";
  341. $sql = 'SELECT p.rowid, p.printer_name, p.printer_location, p.printer_id, p.copy, p.module, p.driver, p.userid, u.login FROM '.MAIN_DB_PREFIX.'printing as p, '.MAIN_DB_PREFIX.'user as u WHERE p.userid=u.rowid';
  342. $resql = $db->query($sql);
  343. while ($row = $db->fetch_array($resql)) {
  344. print '<tr class="oddeven">';
  345. print '<td>'.$row['login'].'</td>';
  346. print '<td>'.$row['module'].'</td>';
  347. print '<td>'.$row['driver'].'</td>';
  348. print '<td>'.$row['printer_name'].'</td>';
  349. print '<td>'.$row['printer_location'].'</td>';
  350. print '<td>'.$row['printer_id'].'</td>';
  351. print '<td>'.$row['copy'].'</td>';
  352. print '<td class="center">'.img_picto($langs->trans("Delete"), 'delete').'</td>';
  353. print "</tr>\n";
  354. }
  355. print '</table>';
  356. print '</div>';
  357. }
  358. print dol_get_fiche_end();
  359. // End of page
  360. llxFooter();
  361. $db->close();