provider.class.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  1. <?php
  2. /**
  3. * ---------------------------------------------------------------------
  4. * SingleSignOn is a plugin which allows to use SSO for auth
  5. * ---------------------------------------------------------------------
  6. * Copyright (C) 2022 Edgard
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. * ---------------------------------------------------------------------
  21. * @copyright Copyright © 2021 - 2022 Edgard
  22. * @license http://www.gnu.org/licenses/gpl.txt GPLv3+
  23. * @link https://github.com/edgardmessias/glpi-singlesignon/
  24. * ---------------------------------------------------------------------
  25. */
  26. class PluginSinglesignonProvider extends CommonDBTM {
  27. // From CommonDBTM
  28. public $dohistory = true;
  29. static $rightname = 'config';
  30. /**
  31. * @var array
  32. */
  33. static $default = null;
  34. /**
  35. *
  36. * @var string
  37. */
  38. protected $_code = null;
  39. /**
  40. *
  41. * @var null|string
  42. */
  43. protected $_token = null;
  44. /**
  45. *
  46. * @var null|array
  47. */
  48. protected $_resource_owner = null;
  49. public $debug = false;
  50. public static function canCreate() {
  51. return static::canUpdate();
  52. }
  53. public static function canDelete() {
  54. return static::canUpdate();
  55. }
  56. public static function canPurge() {
  57. return static::canUpdate();
  58. }
  59. public static function canView() {
  60. return static::canUpdate();
  61. }
  62. // Should return the localized name of the type
  63. static function getTypeName($nb = 0) {
  64. return __sso('Single Sign-on Provider');
  65. }
  66. /**
  67. * @see CommonGLPI::getMenuName()
  68. * */
  69. static function getMenuName() {
  70. return __sso('Single Sign-on');
  71. }
  72. function defineTabs($options = []) {
  73. $ong = [];
  74. $this->addDefaultFormTab($ong);
  75. $this->addStandardTab(__CLASS__, $ong, $options);
  76. $this->addStandardTab('Log', $ong, $options);
  77. return $ong;
  78. }
  79. function post_getEmpty() {
  80. $this->fields["type"] = 'generic';
  81. $this->fields["is_active"] = 1;
  82. }
  83. function showForm($ID, $options = []) {
  84. global $CFG_GLPI;
  85. $this->initForm($ID, $options);
  86. $this->showFormHeader($options);
  87. if (empty($this->fields["type"])) {
  88. $this->fields["type"] = 'generic';
  89. }
  90. echo "<tr class='tab_bg_1'>";
  91. echo "<td>" . __('Name') . "</td>";
  92. echo "<td>";
  93. echo Html::input("name", ['value' => $this->fields["name"], 'class' => 'form-control']);
  94. echo "</td>";
  95. echo "<td>" . __('Comments') . "</td>";
  96. echo "<td>";
  97. echo "<textarea name='comment' >" . $this->fields["comment"] . "</textarea>";
  98. echo "</td></tr>";
  99. $on_change = 'var _value = this.options[this.selectedIndex].value; $(".sso_url").toggle(_value == "generic");';
  100. echo "<tr class='tab_bg_1'>";
  101. echo "<td>" . __sso('SSO Type') . "</td><td>";
  102. self::dropdownType('type', ['value' => $this->fields["type"], 'on_change' => $on_change]);
  103. echo "<td>" . __('Active') . "</td>";
  104. echo "<td>";
  105. Dropdown::showYesNo("is_active", $this->fields["is_active"]);
  106. echo "</td></tr>\n";
  107. echo "<tr class='tab_bg_1'>";
  108. echo "<td>" . __sso('Client ID') . "</td>";
  109. echo "<td><input type='text' style='width:96%' name='client_id' value='" . $this->fields["client_id"] . "'></td>";
  110. echo "<td>" . __sso('Client Secret') . "</td>";
  111. echo "<td><input type='text' style='width:96%' name='client_secret' value='" . $this->fields["client_secret"] . "'></td>";
  112. echo "</tr>\n";
  113. $url_style = "";
  114. if ($this->fields["type"] != 'generic') {
  115. $url_style = 'style="display: none;"';
  116. }
  117. echo "<tr class='tab_bg_1'>";
  118. echo "<td>" . __sso('Scope') . "</td>";
  119. echo "<td><input type='text' style='width:96%' name='scope' value='" . $this->getScope() . "'></td>";
  120. echo "<td>" . __sso('Extra Options') . "</td>";
  121. echo "<td><input type='text' style='width:96%' name='extra_options' value='" . $this->fields["extra_options"] . "'></td>";
  122. echo "</tr>\n";
  123. echo "<tr class='tab_bg_1 sso_url' $url_style>";
  124. echo "<td>" . __sso('Authorize URL') . "</td>";
  125. echo "<td colspan='3'><input type='text' style='width:96%' name='url_authorize' value='" . $this->getAuthorizeUrl() . "'></td>";
  126. echo "</tr>\n";
  127. echo "<tr class='tab_bg_1 sso_url' $url_style>";
  128. echo "<td>" . __sso('Access Token URL') . "</td>";
  129. echo "<td colspan='3'><input type='text' style='width:96%' name='url_access_token' value='" . $this->getAccessTokenUrl() . "'></td>";
  130. echo "</tr>\n";
  131. echo "<tr class='tab_bg_1 sso_url' $url_style>";
  132. echo "<td>" . __sso('Resource Owner Details URL') . "</td>";
  133. echo "<td colspan='3'><input type='text' style='width:96%' name='url_resource_owner_details' value='" . $this->getResourceOwnerDetailsUrl() . "'></td>";
  134. echo "</tr>\n";
  135. echo "<tr class='tab_bg_1'>";
  136. echo "<td>" . __('IsDefault', 'singlesignon') . "</td><td>";
  137. Dropdown::showYesNo("is_default", $this->fields["is_default"]);
  138. echo "<td>" . __sso('PopupAuth') . "</td>";
  139. echo "<td>";
  140. Dropdown::showYesNo("popup", $this->fields["popup"]);
  141. echo "</td></tr>\n";
  142. echo "<tr class='tab_bg_1'>";
  143. echo "<td>" . __sso('SplitDomain') . "</td>";
  144. echo "<td>";
  145. Dropdown::showYesNo("split_domain", $this->fields["split_domain"]);
  146. echo "</td>";
  147. echo "<td>" . __sso('AuthorizedDomains');
  148. echo "&nbsp;";
  149. Html::showToolTip(nl2br(__sso('AuthorizedDomainsTooltip')));
  150. echo "</td>";
  151. echo "<td><input type='text' style='width:96%' name='authorized_domains' value='" . $this->fields["authorized_domains"] . "'></td>";
  152. echo "</td></tr>\n";
  153. echo "<tr class='tab_bg_1'>";
  154. echo "<th colspan='4'>" . __('Personalization') . "</th>";
  155. echo "</tr>\n";
  156. echo "<tr class='tab_bg_1'>";
  157. echo "<td>" . __('Background color') . "</td>";
  158. echo "<td>";
  159. Html::showColorField(
  160. 'bgcolor',
  161. [
  162. 'value' => $this->fields['bgcolor'],
  163. ]
  164. );
  165. echo "&nbsp;";
  166. echo Html::getCheckbox([
  167. 'title' => __('Clear'),
  168. 'name' => '_blank_bgcolor',
  169. 'checked' => empty($this->fields['bgcolor']),
  170. ]);
  171. echo "&nbsp;" . __('Clear');
  172. echo "</td>";
  173. echo "<td>" . __('Color') . "</td>";
  174. echo "<td>";
  175. Html::showColorField(
  176. 'color',
  177. [
  178. 'value' => $this->fields['color'],
  179. ]
  180. );
  181. echo "&nbsp;";
  182. echo Html::getCheckbox([
  183. 'title' => __('Clear'),
  184. 'name' => '_blank_color',
  185. 'checked' => empty($this->fields['color']),
  186. ]);
  187. echo "&nbsp;" . __('Clear');
  188. echo "</td>";
  189. echo "</tr>\n";
  190. echo "<tr class='tab_bg_1'>";
  191. echo "<td>" . __('Picture') . "</td>";
  192. echo "<td colspan='3'>";
  193. if (!empty($this->fields['picture'])) {
  194. echo Html::image(PluginSinglesignonToolbox::getPictureUrl($this->fields['picture']), [
  195. 'style' => '
  196. max-width: 100px;
  197. max-height: 100px;
  198. background-image: linear-gradient(45deg, #b0b0b0 25%, transparent 25%), linear-gradient(-45deg, #b0b0b0 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #b0b0b0 75%), linear-gradient(-45deg, transparent 75%, #b0b0b0 75%);
  199. background-size: 10px 10px;
  200. background-position: 0 0, 0 5px, 5px -5px, -5px 0px;',
  201. 'class' => 'picture_square'
  202. ]);
  203. echo "&nbsp;";
  204. echo Html::getCheckbox([
  205. 'title' => __('Clear'),
  206. 'name' => '_blank_picture'
  207. ]);
  208. echo "&nbsp;" . __('Clear');
  209. } else {
  210. echo Html::file([
  211. 'name' => 'picture',
  212. 'onlyimages' => true,
  213. ]);
  214. }
  215. echo "</td>";
  216. echo "</tr>\n";
  217. echo '<script type="text/javascript">
  218. $("[name=bgcolor]").on("change", function (e) {
  219. $("[name=_blank_bgcolor]").prop("checked", false).attr("checked", false);
  220. });
  221. $("[name=color]").on("change", function (e) {
  222. $("[name=_blank_color]").prop("checked", false).attr("checked", false);
  223. });
  224. </script>';
  225. if ($ID) {
  226. echo "<tr class='tab_bg_1'>";
  227. echo "<th colspan='4'>" . __('Test') . "</th>";
  228. echo "</tr>\n";
  229. $url = PluginSinglesignonToolbox::getCallbackUrl($ID);
  230. $fullUrl = $this->getBaseURL() . $url;
  231. echo "<tr class='tab_bg_1'>";
  232. echo "<td>" . __sso('Callback URL') . "</td>";
  233. echo "<td colspan='3'><a id='singlesignon_callbackurl' href='$fullUrl' data-url='$url'>$fullUrl</a></td>";
  234. echo "</tr>\n";
  235. $options['addbuttons'] = ['test_singlesignon' => __sso('Test Single Sign-on')];
  236. }
  237. $this->showFormButtons($options);
  238. if ($ID) {
  239. echo '<script type="text/javascript">
  240. $("[name=test_singlesignon]").on("click", function (e) {
  241. e.preventDefault();
  242. var url = $("#singlesignon_callbackurl").attr("data-url") + "/test/1";
  243. var left = ($(window).width()/2)-(600/2);
  244. var top = ($(window).height()/2)-(800/2);
  245. var newWindow = window.open(url, "singlesignon", "width=600,height=800,left=" + left + ",top=" + top);
  246. if (window.focus) {
  247. newWindow.focus();
  248. }
  249. });
  250. </script>';
  251. }
  252. return true;
  253. }
  254. function prepareInputForAdd($input) {
  255. return $this->prepareInput($input);
  256. }
  257. function prepareInputForUpdate($input) {
  258. return $this->prepareInput($input);
  259. }
  260. function cleanDBonPurge() {
  261. PluginSinglesignonToolbox::deletePicture($this->fields['picture']);
  262. $this->deleteChildrenAndRelationsFromDb(
  263. [
  264. 'PluginSinglesignonProvider_User',
  265. ]
  266. );
  267. }
  268. /**
  269. * Prepares input (for update and add)
  270. *
  271. * @param array $input Input data
  272. *
  273. * @return array
  274. */
  275. private function prepareInput($input) {
  276. $error_detected = [];
  277. $type = '';
  278. //check for requirements
  279. if (isset($input['type'])) {
  280. $type = $input['type'];
  281. }
  282. if (!isset($input['name']) || empty($input['name'])) {
  283. $error_detected[] = __sso('A Name is required');
  284. }
  285. if (empty($type)) {
  286. $error_detected[] = __('An item type is required');
  287. } else if (!isset(static::getTypes()[$type])) {
  288. $error_detected[] = sprintf(__sso('The "%s" is a Invalid type'), $type);
  289. }
  290. if (!isset($input['client_id']) || empty($input['client_id'])) {
  291. $error_detected[] = __sso('A Client ID is required');
  292. }
  293. if (!isset($input['client_secret']) || empty($input['client_secret'])) {
  294. $error_detected[] = __sso('A Client Secret is required');
  295. }
  296. if ($type === 'generic') {
  297. if (!isset($input['url_authorize']) || empty($input['url_authorize'])) {
  298. $error_detected[] = __sso('An Authorize URL is required');
  299. } else if (!filter_var($input['url_authorize'], FILTER_VALIDATE_URL)) {
  300. $error_detected[] = __sso('The Authorize URL is invalid');
  301. }
  302. if (!isset($input['url_access_token']) || empty($input['url_access_token'])) {
  303. $error_detected[] = __sso('An Access Token URL is required');
  304. } else if (!filter_var($input['url_access_token'], FILTER_VALIDATE_URL)) {
  305. $error_detected[] = __sso('The Access Token URL is invalid');
  306. }
  307. if (!isset($input['url_resource_owner_details']) || empty($input['url_resource_owner_details'])) {
  308. $error_detected[] = __sso('A Resource Owner Details URL is required');
  309. } else if (!filter_var($input['url_resource_owner_details'], FILTER_VALIDATE_URL)) {
  310. $error_detected[] = __sso('The Resource Owner Details URL is invalid');
  311. }
  312. }
  313. if (count($error_detected)) {
  314. foreach ($error_detected as $error) {
  315. Session::addMessageAfterRedirect(
  316. $error,
  317. true,
  318. ERROR
  319. );
  320. }
  321. return false;
  322. }
  323. if (isset($input["_blank_bgcolor"])
  324. && $input["_blank_bgcolor"]
  325. ) {
  326. $input['bgcolor'] = '';
  327. }
  328. if (isset($input["_blank_color"])
  329. && $input["_blank_color"]
  330. ) {
  331. $input['color'] = '';
  332. }
  333. if (isset($input["_blank_picture"])
  334. && $input["_blank_picture"]
  335. ) {
  336. $input['picture'] = '';
  337. if (array_key_exists('picture', $this->fields)) {
  338. PluginSinglesignonToolbox::deletePicture($this->fields['picture']);
  339. }
  340. }
  341. if (isset($input["_picture"])) {
  342. $picture = array_shift($input["_picture"]);
  343. if ($dest = PluginSinglesignonToolbox::savePicture(GLPI_TMP_DIR . '/' . $picture)) {
  344. $input['picture'] = $dest;
  345. } else {
  346. Session::addMessageAfterRedirect(__('Unable to save picture file.'), true, ERROR);
  347. }
  348. if (array_key_exists('picture', $this->fields)) {
  349. PluginSinglesignonToolbox::deletePicture($this->fields['picture']);
  350. }
  351. }
  352. return $input;
  353. }
  354. function getSearchOptions() {
  355. // For GLPI <= 9.2
  356. $options = [];
  357. foreach ($this->rawSearchOptions() as $opt) {
  358. if (!isset($opt['id'])) {
  359. continue;
  360. }
  361. $optid = $opt['id'];
  362. unset($opt['id']);
  363. if (isset($options[$optid])) {
  364. $message = "Duplicate key $optid ({$options[$optid]['name']}/{$opt['name']}) in " .
  365. get_class($this) . " searchOptions!";
  366. Toolbox::logDebug($message);
  367. }
  368. foreach ($opt as $k => $v) {
  369. $options[$optid][$k] = $v;
  370. }
  371. }
  372. return $options;
  373. }
  374. function rawSearchOptions() {
  375. $tab = [];
  376. $tab[] = [
  377. 'id' => 'common',
  378. 'name' => __('Characteristics'),
  379. ];
  380. $tab[] = [
  381. 'id' => 1,
  382. 'table' => $this->getTable(),
  383. 'field' => 'name',
  384. 'name' => __('Name'),
  385. 'datatype' => 'itemlink',
  386. ];
  387. $tab[] = [
  388. 'id' => 2,
  389. 'table' => $this->getTable(),
  390. 'field' => 'type',
  391. 'name' => __('Type'),
  392. 'searchtype' => 'equals',
  393. 'datatype' => 'specific',
  394. ];
  395. $tab[] = [
  396. 'id' => 3,
  397. 'table' => $this->getTable(),
  398. 'field' => 'client_id',
  399. 'name' => __sso('Client ID'),
  400. 'datatype' => 'text',
  401. ];
  402. $tab[] = [
  403. 'id' => 4,
  404. 'table' => $this->getTable(),
  405. 'field' => 'client_secret',
  406. 'name' => __sso('Client Secret'),
  407. 'datatype' => 'text',
  408. ];
  409. $tab[] = [
  410. 'id' => 5,
  411. 'table' => $this->getTable(),
  412. 'field' => 'scope',
  413. 'name' => __sso('Scope'),
  414. 'datatype' => 'text',
  415. ];
  416. $tab[] = [
  417. 'id' => 6,
  418. 'table' => $this->getTable(),
  419. 'field' => 'extra_options',
  420. 'name' => __sso('Extra Options'),
  421. 'datatype' => 'specific',
  422. ];
  423. $tab[] = [
  424. 'id' => 7,
  425. 'table' => $this->getTable(),
  426. 'field' => 'url_authorize',
  427. 'name' => __sso('Authorize URL'),
  428. 'datatype' => 'weblink',
  429. ];
  430. $tab[] = [
  431. 'id' => 8,
  432. 'table' => $this->getTable(),
  433. 'field' => 'url_access_token',
  434. 'name' => __sso('Access Token URL'),
  435. 'datatype' => 'weblink',
  436. ];
  437. $tab[] = [
  438. 'id' => 9,
  439. 'table' => $this->getTable(),
  440. 'field' => 'url_resource_owner_details',
  441. 'name' => __sso('Resource Owner Details URL'),
  442. 'datatype' => 'weblink',
  443. ];
  444. $tab[] = [
  445. 'id' => 10,
  446. 'table' => $this->getTable(),
  447. 'field' => 'is_active',
  448. 'name' => __('Active'),
  449. 'searchtype' => 'equals',
  450. 'datatype' => 'bool',
  451. ];
  452. $tab[] = [
  453. 'id' => 30,
  454. 'table' => $this->getTable(),
  455. 'field' => 'id',
  456. 'name' => __('ID'),
  457. 'datatype' => 'itemlink',
  458. ];
  459. return $tab;
  460. }
  461. static function getSpecificValueToDisplay($field, $values, array $options = []) {
  462. if (!is_array($values)) {
  463. $values = [$field => $values];
  464. }
  465. switch ($field) {
  466. case 'type':
  467. return self::getTicketTypeName($values[$field]);
  468. case 'extra_options':
  469. return '<pre>' . $values[$field] . '</pre>';
  470. }
  471. return '';
  472. }
  473. static function getSpecificValueToSelect($field, $name = '', $values = '', array $options = []) {
  474. if (!is_array($values)) {
  475. $values = [$field => $values];
  476. }
  477. $options['display'] = false;
  478. switch ($field) {
  479. case 'type':
  480. $options['value'] = $values[$field];
  481. return self::dropdownType($name, $options);
  482. }
  483. return parent::getSpecificValueToSelect($field, $name, $values, $options);
  484. }
  485. /**
  486. * Get ticket types
  487. *
  488. * @return array of types
  489. * */
  490. static function getTypes() {
  491. $options['generic'] = __sso('Generic');
  492. $options['azure'] = __sso('Azure');
  493. $options['facebook'] = __sso('Facebook');
  494. $options['github'] = __sso('GitHub');
  495. $options['google'] = __sso('Google');
  496. $options['instagram'] = __sso('Instagram');
  497. $options['linkedin'] = __sso('LinkdeIn');
  498. return $options;
  499. }
  500. /**
  501. * Get ticket type Name
  502. *
  503. * @param $value type ID
  504. * */
  505. static function getTicketTypeName($value) {
  506. $tab = static::getTypes();
  507. // Return $value if not defined
  508. return (isset($tab[$value]) ? $tab[$value] : $value);
  509. }
  510. /**
  511. * Dropdown of ticket type
  512. *
  513. * @param $name select name
  514. * @param $options array of options:
  515. * - value : integer / preselected value (default 0)
  516. * - toadd : array / array of specific values to add at the begining
  517. * - on_change : string / value to transmit to "onChange"
  518. * - display : boolean / display or get string (default true)
  519. *
  520. * @return string id of the select
  521. * */
  522. static function dropdownType($name, $options = []) {
  523. $params['value'] = 0;
  524. $params['toadd'] = [];
  525. $params['on_change'] = '';
  526. $params['display'] = true;
  527. if (is_array($options) && count($options)) {
  528. foreach ($options as $key => $val) {
  529. $params[$key] = $val;
  530. }
  531. }
  532. $items = [];
  533. if (count($params['toadd']) > 0) {
  534. $items = $params['toadd'];
  535. }
  536. $items += self::getTypes();
  537. return Dropdown::showFromArray($name, $items, $params);
  538. }
  539. /**
  540. * Get an history entry message
  541. *
  542. * @param $data Array from glpi_logs table
  543. *
  544. * @since GLPI version 0.84
  545. *
  546. * @return string
  547. * */
  548. static function getHistoryEntry($data) {
  549. switch ($data['linked_action'] - Log::HISTORY_PLUGIN) {
  550. case 0:
  551. return __('History from plugin example', 'example');
  552. }
  553. return '';
  554. }
  555. //////////////////////////////
  556. ////// SPECIFIC MODIF MASSIVE FUNCTIONS ///////
  557. /**
  558. * @since version 0.85
  559. *
  560. * @see CommonDBTM::getSpecificMassiveActions()
  561. * */
  562. function getSpecificMassiveActions($checkitem = null) {
  563. $actions = parent::getSpecificMassiveActions($checkitem);
  564. $actions['Document_Item' . MassiveAction::CLASS_ACTION_SEPARATOR . 'add'] = _x('button', 'Add a document'); // GLPI core one
  565. $actions[__CLASS__ . MassiveAction::CLASS_ACTION_SEPARATOR . 'do_nothing'] = __('Do Nothing - just for fun', 'example'); // Specific one
  566. return $actions;
  567. }
  568. /**
  569. * @since version 0.85
  570. *
  571. * @see CommonDBTM::showMassiveActionsSubForm()
  572. * */
  573. static function showMassiveActionsSubForm(MassiveAction $ma) {
  574. switch ($ma->getAction()) {
  575. case 'DoIt':
  576. echo "&nbsp;<input type='hidden' name='toto' value='1'>" .
  577. Html::submit(_x('button', 'Post'), ['name' => 'massiveaction']) .
  578. " " . __('Write in item history', 'example');
  579. return true;
  580. case 'do_nothing':
  581. echo "&nbsp;" . Html::submit(_x('button', 'Post'), ['name' => 'massiveaction']) .
  582. " " . __('but do nothing :)', 'example');
  583. return true;
  584. }
  585. return parent::showMassiveActionsSubForm($ma);
  586. }
  587. /**
  588. * @since version 0.85
  589. *
  590. * @see CommonDBTM::processMassiveActionsForOneItemtype()
  591. * */
  592. static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item, array $ids) {
  593. global $DB;
  594. switch ($ma->getAction()) {
  595. case 'DoIt':
  596. if ($item->getType() == 'Computer') {
  597. Session::addMessageAfterRedirect(__("Right it is the type I want...", 'example'));
  598. Session::addMessageAfterRedirect(__('Write in item history', 'example'));
  599. $changes = [0, 'old value', 'new value'];
  600. foreach ($ids as $id) {
  601. if ($item->getFromDB($id)) {
  602. Session::addMessageAfterRedirect("- " . $item->getField("name"));
  603. Log::history($id, 'Computer', $changes, 'PluginExampleExample', Log::HISTORY_PLUGIN);
  604. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
  605. } else {
  606. // Example of ko count
  607. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
  608. }
  609. }
  610. } else {
  611. // When nothing is possible ...
  612. $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);
  613. }
  614. return;
  615. case 'do_nothing':
  616. if ($item->getType() == 'PluginExampleExample') {
  617. Session::addMessageAfterRedirect(__("Right it is the type I want...", 'example'));
  618. Session::addMessageAfterRedirect(__("But... I say I will do nothing for:", 'example'));
  619. foreach ($ids as $id) {
  620. if ($item->getFromDB($id)) {
  621. Session::addMessageAfterRedirect("- " . $item->getField("name"));
  622. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
  623. } else {
  624. // Example for noright / Maybe do it with can function is better
  625. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
  626. }
  627. }
  628. } else {
  629. $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);
  630. }
  631. return;
  632. }
  633. parent::processMassiveActionsForOneItemtype($ma, $item, $ids);
  634. }
  635. static function getIcon() {
  636. return "fas fa-user-lock";
  637. }
  638. public static function getDefault($type, $key, $default = null) {
  639. if (static::$default === null) {
  640. $content = file_get_contents(dirname(__FILE__) . '/../providers.json');
  641. static::$default = json_decode($content, true);
  642. }
  643. if (isset(static::$default[$type]) && static::$default[$type][$key]) {
  644. return static::$default[$type][$key];
  645. }
  646. return $default;
  647. }
  648. public function getClientType() {
  649. $value = "generic";
  650. if (isset($this->fields['type']) && !empty($this->fields['type'])) {
  651. $value = $this->fields['type'];
  652. }
  653. return $value;
  654. }
  655. public function getClientId() {
  656. $value = "";
  657. if (isset($this->fields['client_id']) && !empty($this->fields['client_id'])) {
  658. $value = $this->fields['client_id'];
  659. }
  660. return $value;
  661. }
  662. public function getClientSecret() {
  663. $value = "";
  664. if (isset($this->fields['client_secret']) && !empty($this->fields['client_secret'])) {
  665. $value = $this->fields['client_secret'];
  666. }
  667. return $value;
  668. }
  669. public function getScope() {
  670. $type = $this->getClientType();
  671. $value = static::getDefault($type, "scope");
  672. $fields = $this->fields;
  673. if (!isset($fields['scope']) || empty($fields['scope'])) {
  674. $fields['scope'] = $value;
  675. }
  676. $fields = Plugin::doHookFunction("sso:scope", $fields);
  677. return $fields['scope'];
  678. }
  679. public function getAuthorizeUrl() {
  680. $type = $this->getClientType();
  681. $value = static::getDefault($type, "url_authorize");
  682. $fields = $this->fields;
  683. if (!isset($fields['url_authorize']) || empty($fields['url_authorize'])) {
  684. $fields['url_authorize'] = $value;
  685. }
  686. $fields = Plugin::doHookFunction("sso:url_authorize", $fields);
  687. return $fields['url_authorize'];
  688. }
  689. public function getAccessTokenUrl() {
  690. $type = $this->getClientType();
  691. $value = static::getDefault($type, "url_access_token");
  692. $fields = $this->fields;
  693. if (!isset($fields['url_access_token']) || empty($fields['url_access_token'])) {
  694. $fields['url_access_token'] = $value;
  695. }
  696. $fields = Plugin::doHookFunction("sso:url_access_token", $fields);
  697. return $fields['url_access_token'];
  698. }
  699. public function getResourceOwnerDetailsUrl($access_token = null) {
  700. $type = $this->getClientType();
  701. $value = static::getDefault($type, "url_resource_owner_details", "");
  702. $fields = $this->fields;
  703. $fields['access_token'] = $access_token;
  704. if (!isset($fields['url_resource_owner_details']) || empty($fields['url_resource_owner_details'])) {
  705. $fields['url_resource_owner_details'] = $value;
  706. }
  707. $fields = Plugin::doHookFunction("sso:url_resource_owner_details", $fields);
  708. $url = $fields['url_resource_owner_details'];
  709. $url = str_replace("<access_token>", $access_token, $url);
  710. $url = str_replace("<appsecret_proof>", hash_hmac('sha256', $access_token, $this->getClientSecret()), $url);
  711. return $url;
  712. }
  713. /**
  714. * Get current URL without query string
  715. * @return string
  716. */
  717. private function getBaseURL() {
  718. $baseURL = "";
  719. if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
  720. $baseURL = ($_SERVER["HTTP_X_FORWARDED_PROTO"] == "https") ? "https://" : "http://";
  721. } else if (isset($_SERVER["HTTPS"])) {
  722. $baseURL = ($_SERVER["HTTPS"] == "on") ? "https://" : "http://";
  723. } else {
  724. $baseURL = "http://";
  725. }
  726. if (isset($_SERVER["HTTP_X_FORWARDED_HOST"])) {
  727. $baseURL .= $_SERVER["HTTP_X_FORWARDED_HOST"];
  728. } else if (isset($_SERVER["HTTP_X_FORWARDED_HOST"])) {
  729. $baseURL .= $_SERVER["HTTP_X_FORWARDED_HOST"];
  730. } else {
  731. $baseURL .= $_SERVER["SERVER_NAME"];
  732. }
  733. $port = $_SERVER["SERVER_PORT"];
  734. if (isset($_SERVER["HTTP_X_FORWARDED_PORT"])) {
  735. $port = $_SERVER["HTTP_X_FORWARDED_PORT"];
  736. }
  737. if ($port != "80" && $port != "443") {
  738. $baseURL .= ":" . $_SERVER["SERVER_PORT"];
  739. }
  740. return $baseURL;
  741. }
  742. /**
  743. * Get current URL without query string
  744. * @return string
  745. */
  746. private function getCurrentURL() {
  747. $currentURL = $this->getBaseURL();
  748. // $currentURL .= $_SERVER["REQUEST_URI"];
  749. // Ignore Query String
  750. if (isset($_SERVER["SCRIPT_NAME"])) {
  751. $currentURL .= $_SERVER["SCRIPT_NAME"];
  752. }
  753. if (isset($_SERVER["PATH_INFO"])) {
  754. $currentURL .= $_SERVER["PATH_INFO"];
  755. }
  756. return $currentURL;
  757. }
  758. /**
  759. *
  760. * @return boolean|string
  761. */
  762. public function checkAuthorization() {
  763. if (isset($_GET['error'])) {
  764. $error_description = isset($_GET['error_description']) ? $_GET['error_description'] : __("The action you have requested is not allowed.");
  765. Html::displayErrorAndDie(__($error_description), true);
  766. }
  767. if (!isset($_GET['code'])) {
  768. $state = Session::getNewCSRFToken();
  769. if (isset($_SESSION['redirect'])) {
  770. $state .= "&redirect=" . $_SESSION['redirect'];
  771. }
  772. $params = [
  773. 'client_id' => $this->getClientId(),
  774. 'scope' => $this->getScope(),
  775. 'state' => $state,
  776. 'response_type' => 'code',
  777. 'approval_prompt' => 'auto',
  778. 'redirect_uri' => $this->getCurrentURL(),
  779. ];
  780. $params = Plugin::doHookFunction("sso:authorize_params", $params);
  781. $url = $this->getAuthorizeUrl();
  782. $glue = strstr($url, '?') === false ? '?' : '&';
  783. $url .= $glue . http_build_query($params);
  784. header('Location: ' . $url);
  785. exit;
  786. }
  787. if (isset($_GET['state']) && is_integer(strpos($_GET['state'], "&redirect="))) {
  788. $pos_redirect = strpos($_GET['state'], "&redirect=");
  789. $state = substr($_GET['state'], 0, $pos_redirect);
  790. $_GET['state'] = substr($_GET['state'], $pos_redirect);
  791. } else {
  792. $state = isset($_GET['state']) ? $_GET['state'] : '';
  793. }
  794. // Check given state against previously stored one to mitigate CSRF attack
  795. Session::checkCSRF([
  796. '_glpi_csrf_token' => $state,
  797. ]);
  798. $this->_code = $_GET['code'];
  799. return $_GET['code'];
  800. }
  801. /**
  802. *
  803. * @return boolean|string
  804. */
  805. public function getAccessToken() {
  806. if ($this->_token !== null) {
  807. return $this->_token;
  808. }
  809. if ($this->_code === null) {
  810. return false;
  811. }
  812. $params = [
  813. 'client_id' => $this->getClientId(),
  814. 'client_secret' => $this->getClientSecret(),
  815. 'redirect_uri' => $this->getCurrentURL(),
  816. 'grant_type' => 'authorization_code',
  817. 'code' => $this->_code,
  818. ];
  819. $params = Plugin::doHookFunction("sso:access_token_params", $params);
  820. $url = $this->getAccessTokenUrl();
  821. $content = Toolbox::callCurl($url, [
  822. CURLOPT_HTTPHEADER => [
  823. "Accept: application/json",
  824. ],
  825. CURLOPT_POST => true,
  826. CURLOPT_POSTFIELDS => http_build_query($params),
  827. CURLOPT_SSL_VERIFYHOST => false,
  828. CURLOPT_SSL_VERIFYPEER => false,
  829. ]);
  830. if ($this->debug) {
  831. print_r("\ngetAccessToken:\n");
  832. }
  833. try {
  834. $data = json_decode($content, true);
  835. if ($this->debug) {
  836. print_r($data);
  837. }
  838. if (!isset($data['access_token'])) {
  839. return false;
  840. }
  841. $this->_token = $data['access_token'];
  842. } catch (\Exception $ex) {
  843. if ($this->debug) {
  844. print_r($content);
  845. }
  846. return false;
  847. }
  848. return $this->_token;
  849. }
  850. /**
  851. *
  852. * @return boolean|array
  853. */
  854. public function getResourceOwner() {
  855. if ($this->_resource_owner !== null) {
  856. return $this->_resource_owner;
  857. }
  858. $token = $this->getAccessToken();
  859. if (!$token) {
  860. return false;
  861. }
  862. $url = $this->getResourceOwnerDetailsUrl($token);
  863. $headers = [
  864. "Accept:application/json",
  865. "Authorization:Bearer $token",
  866. ];
  867. $headers = Plugin::doHookFunction("sso:resource_owner_header", $headers);
  868. $content = Toolbox::callCurl($url, [
  869. CURLOPT_HTTPHEADER => $headers,
  870. CURLOPT_SSL_VERIFYHOST => false,
  871. CURLOPT_SSL_VERIFYPEER => false,
  872. ]);
  873. if ($this->debug) {
  874. print_r("\ngetResourceOwner:\n");
  875. }
  876. try {
  877. $data = json_decode($content, true);
  878. if ($this->debug) {
  879. print_r($data);
  880. }
  881. $this->_resource_owner = $data;
  882. } catch (\Exception $ex) {
  883. if ($this->debug) {
  884. print_r($content);
  885. }
  886. return false;
  887. }
  888. if ($this->getClientType() === "linkedin") {
  889. if ($this->debug) {
  890. print_r("\nlinkedin:\n");
  891. }
  892. $email_url = "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))";
  893. $content = Toolbox::callCurl($email_url, [
  894. CURLOPT_HTTPHEADER => $headers,
  895. CURLOPT_SSL_VERIFYHOST => false,
  896. CURLOPT_SSL_VERIFYPEER => false,
  897. ]);
  898. try {
  899. $data = json_decode($content, true);
  900. if ($this->debug) {
  901. print_r($content);
  902. }
  903. $this->_resource_owner['email-address'] = $data['elements'][0]['handle~']['emailAddress'];
  904. } catch (\Exception $ex) {
  905. return false;
  906. }
  907. }
  908. return $this->_resource_owner;
  909. }
  910. public function findUser() {
  911. $resource_array = $this->getResourceOwner();
  912. if (!$resource_array) {
  913. return false;
  914. }
  915. $user = new User();
  916. //First: check linked user
  917. $id = Plugin::doHookFunction("sso:find_user", $resource_array);
  918. if (is_numeric($id) && $user->getFromDB($id)) {
  919. return $user;
  920. }
  921. $remote_id = false;
  922. $remote_id_fields = ['id', 'username'];
  923. foreach ($remote_id_fields as $field) {
  924. if (isset($resource_array[$field]) && !empty($resource_array[$field])) {
  925. $remote_id = $resource_array[$field];
  926. break;
  927. }
  928. }
  929. if ($remote_id) {
  930. $link = new PluginSinglesignonProvider_User();
  931. $condition = "`remote_id` = '{$remote_id}' AND `plugin_singlesignon_providers_id` = {$this->fields['id']}";
  932. if (version_compare(GLPI_VERSION, '9.4', '>=')) {
  933. $condition = [$condition];
  934. }
  935. $links = $link->find($condition);
  936. if (!empty($links) && $first = reset($links)) {
  937. $id = $first['users_id'];
  938. }
  939. $remote_id;
  940. }
  941. if (is_numeric($id) && $user->getFromDB($id)) {
  942. return $user;
  943. }
  944. $split = $this->fields['split_domain'];
  945. $login = false;
  946. $login_fields = ['userPrincipalName','login', 'username', 'id'];
  947. foreach ($login_fields as $field) {
  948. if (isset($resource_array[$field]) && is_string($resource_array[$field])) {
  949. $login = $resource_array[$field];
  950. $isAuthorized = empty($authorizedDomains);
  951. foreach ($authorizedDomains as $authorizedDomain) {
  952. if (preg_match("/{$authorizedDomain}$/i", $login)) {
  953. $isAuthorized = true;
  954. }
  955. }
  956. if (!$isAuthorized) {
  957. return false;
  958. }
  959. if ($split) {
  960. $loginSplit = explode("@", $login);
  961. $login = $loginSplit[0];
  962. }
  963. break;
  964. }
  965. }
  966. if ($login && $user->getFromDBbyName($login)) {
  967. return $user;
  968. }
  969. $email = false;
  970. $email_fields = ['email', 'e-mail', 'email-address', 'mail'];
  971. $authorizedDomainsString = $this->fields['authorized_domains'];
  972. $authorizedDomains = [];
  973. if (isset($authorizedDomainsString)) {
  974. $authorizedDomains = explode(',', $authorizedDomainsString);
  975. }
  976. foreach ($email_fields as $field) {
  977. if (isset($resource_array[$field]) && is_string($resource_array[$field])) {
  978. $email = $resource_array[$field];
  979. $isAuthorized = empty($authorizedDomains);
  980. foreach ($authorizedDomains as $authorizedDomain) {
  981. if (preg_match("/{$authorizedDomain}$/i", $email)) {
  982. $isAuthorized = true;
  983. }
  984. }
  985. if (!$isAuthorized) {
  986. return false;
  987. }
  988. if ($split) {
  989. $emailSplit = explode("@", $email);
  990. $email = $emailSplit[0];
  991. }
  992. break;
  993. }
  994. }
  995. $default_condition = '';
  996. if (version_compare(GLPI_VERSION, '9.3', '>=')) {
  997. $default_condition = [];
  998. }
  999. if ($email && $user->getFromDBbyEmail($email, $default_condition)) {
  1000. return $user;
  1001. }
  1002. return false;
  1003. }
  1004. public function login() {
  1005. $user = $this->findUser();
  1006. if (!$user) {
  1007. return false;
  1008. }
  1009. //Create fake auth
  1010. $auth = new Auth();
  1011. $auth->user = $user;
  1012. $auth->auth_succeded = true;
  1013. $auth->extauth = 1;
  1014. $auth->user_present = $auth->user->getFromDBbyName(addslashes($user->fields['name']));
  1015. $auth->user->fields['authtype'] = Auth::DB_GLPI;
  1016. Session::init($auth);
  1017. return $auth->auth_succeded;
  1018. }
  1019. public function linkUser($user_id) {
  1020. $user = new User();
  1021. if (!$user->getFromDB($user_id)) {
  1022. return false;
  1023. }
  1024. $resource_array = $this->getResourceOwner();
  1025. if (!$resource_array) {
  1026. return false;
  1027. }
  1028. $remote_id = false;
  1029. $id_fields = ['id', 'sub', 'username'];
  1030. foreach ($id_fields as $field) {
  1031. if (isset($resource_array[$field]) && !empty($resource_array[$field])) {
  1032. $remote_id = $resource_array[$field];
  1033. break;
  1034. }
  1035. }
  1036. if (!$remote_id) {
  1037. return false;
  1038. }
  1039. $link = new PluginSinglesignonProvider_User();
  1040. // Unlink from another user
  1041. $link->deleteByCriteria([
  1042. 'plugin_singlesignon_providers_id' => $this->fields['id'],
  1043. 'remote_id' => $remote_id,
  1044. ]);
  1045. return $link->add([
  1046. 'plugin_singlesignon_providers_id' => $this->fields['id'],
  1047. 'users_id' => $user_id,
  1048. 'remote_id' => $remote_id,
  1049. ]);
  1050. }
  1051. }