provider.class.php 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  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 "<td>" . __sso("Use Email as Login") . "<td>";
  155. Dropdown::showYesNo("use_email_for_login", $this->fields["use_email_for_login"]);
  156. echo "</td>";
  157. echo "<td>" . __sso('Split Name') . "<td>";
  158. Dropdown::showYesNo("split_name", $this->fields["split_name"]);
  159. echo "</td>";
  160. echo "<tr class='tab_bg_1'>";
  161. echo "<th colspan='4'>" . __('Personalization') . "</th>";
  162. echo "</tr>\n";
  163. echo "<tr class='tab_bg_1'>";
  164. echo "<td>" . __('Background color') . "</td>";
  165. echo "<td>";
  166. Html::showColorField(
  167. 'bgcolor',
  168. [
  169. 'value' => $this->fields['bgcolor'],
  170. ]
  171. );
  172. echo "&nbsp;";
  173. echo Html::getCheckbox([
  174. 'title' => __('Clear'),
  175. 'name' => '_blank_bgcolor',
  176. 'checked' => empty($this->fields['bgcolor']),
  177. ]);
  178. echo "&nbsp;" . __('Clear');
  179. echo "</td>";
  180. echo "<td>" . __('Color') . "</td>";
  181. echo "<td>";
  182. Html::showColorField(
  183. 'color',
  184. [
  185. 'value' => $this->fields['color'],
  186. ]
  187. );
  188. echo "&nbsp;";
  189. echo Html::getCheckbox([
  190. 'title' => __('Clear'),
  191. 'name' => '_blank_color',
  192. 'checked' => empty($this->fields['color']),
  193. ]);
  194. echo "&nbsp;" . __('Clear');
  195. echo "</td>";
  196. echo "</tr>\n";
  197. echo "<tr class='tab_bg_1'>";
  198. echo "<td>" . __('Picture') . "</td>";
  199. echo "<td colspan='3'>";
  200. if (!empty($this->fields['picture'])) {
  201. echo Html::image(PluginSinglesignonToolbox::getPictureUrl($this->fields['picture']), [
  202. 'style' => '
  203. max-width: 100px;
  204. max-height: 100px;
  205. 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%);
  206. background-size: 10px 10px;
  207. background-position: 0 0, 0 5px, 5px -5px, -5px 0px;',
  208. 'class' => 'picture_square'
  209. ]);
  210. echo "&nbsp;";
  211. echo Html::getCheckbox([
  212. 'title' => __('Clear'),
  213. 'name' => '_blank_picture'
  214. ]);
  215. echo "&nbsp;" . __('Clear');
  216. } else {
  217. echo Html::file([
  218. 'name' => 'picture',
  219. 'onlyimages' => true,
  220. ]);
  221. }
  222. echo "</td>";
  223. echo "</tr>\n";
  224. echo '<script type="text/javascript">
  225. $("[name=bgcolor]").on("change", function (e) {
  226. $("[name=_blank_bgcolor]").prop("checked", false).attr("checked", false);
  227. });
  228. $("[name=color]").on("change", function (e) {
  229. $("[name=_blank_color]").prop("checked", false).attr("checked", false);
  230. });
  231. </script>';
  232. if ($ID) {
  233. echo "<tr class='tab_bg_1'>";
  234. echo "<th colspan='4'>" . __('Test') . "</th>";
  235. echo "</tr>\n";
  236. $url = PluginSinglesignonToolbox::getCallbackUrl($ID);
  237. $fullUrl = $this->getBaseURL() . $url;
  238. echo "<tr class='tab_bg_1'>";
  239. echo "<td>" . __sso('Callback URL') . "</td>";
  240. echo "<td colspan='3'><a id='singlesignon_callbackurl' href='$fullUrl' data-url='$url'>$fullUrl</a></td>";
  241. echo "</tr>\n";
  242. $options['addbuttons'] = ['test_singlesignon' => __sso('Test Single Sign-on')];
  243. }
  244. $this->showFormButtons($options);
  245. if ($ID) {
  246. echo '<script type="text/javascript">
  247. $("[name=test_singlesignon]").on("click", function (e) {
  248. e.preventDefault();
  249. // Im not sure why /test/1 is added here, I got a problem with the redirect_uri because its added after /provider/id
  250. var url = $("#singlesignon_callbackurl").attr("data-url"); // + "/test/1";
  251. var left = ($(window).width()/2)-(600/2);
  252. var top = ($(window).height()/2)-(800/2);
  253. var newWindow = window.open(url, "singlesignon", "width=600,height=800,left=" + left + ",top=" + top);
  254. if (window.focus) {
  255. newWindow.focus();
  256. }
  257. });
  258. </script>';
  259. }
  260. return true;
  261. }
  262. function prepareInputForAdd($input) {
  263. return $this->prepareInput($input);
  264. }
  265. function prepareInputForUpdate($input) {
  266. return $this->prepareInput($input);
  267. }
  268. function cleanDBonPurge() {
  269. PluginSinglesignonToolbox::deletePicture($this->fields['picture']);
  270. $this->deleteChildrenAndRelationsFromDb(
  271. [
  272. 'PluginSinglesignonProvider_User',
  273. ]
  274. );
  275. }
  276. /**
  277. * Prepares input (for update and add)
  278. *
  279. * @param array $input Input data
  280. *
  281. * @return array
  282. */
  283. private function prepareInput($input) {
  284. $error_detected = [];
  285. $type = '';
  286. //check for requirements
  287. if (isset($input['type'])) {
  288. $type = $input['type'];
  289. }
  290. if (!isset($input['name']) || empty($input['name'])) {
  291. $error_detected[] = __sso('A Name is required');
  292. }
  293. if (empty($type)) {
  294. $error_detected[] = __('An item type is required');
  295. } else if (!isset(static::getTypes()[$type])) {
  296. $error_detected[] = sprintf(__sso('The "%s" is a Invalid type'), $type);
  297. }
  298. if (!isset($input['client_id']) || empty($input['client_id'])) {
  299. $error_detected[] = __sso('A Client ID is required');
  300. }
  301. if (!isset($input['client_secret']) || empty($input['client_secret'])) {
  302. $error_detected[] = __sso('A Client Secret is required');
  303. }
  304. if ($type === 'generic') {
  305. if (!isset($input['url_authorize']) || empty($input['url_authorize'])) {
  306. $error_detected[] = __sso('An Authorize URL is required');
  307. } else if (!filter_var($input['url_authorize'], FILTER_VALIDATE_URL)) {
  308. $error_detected[] = __sso('The Authorize URL is invalid');
  309. }
  310. if (!isset($input['url_access_token']) || empty($input['url_access_token'])) {
  311. $error_detected[] = __sso('An Access Token URL is required');
  312. } else if (!filter_var($input['url_access_token'], FILTER_VALIDATE_URL)) {
  313. $error_detected[] = __sso('The Access Token URL is invalid');
  314. }
  315. if (!isset($input['url_resource_owner_details']) || empty($input['url_resource_owner_details'])) {
  316. $error_detected[] = __sso('A Resource Owner Details URL is required');
  317. } else if (!filter_var($input['url_resource_owner_details'], FILTER_VALIDATE_URL)) {
  318. $error_detected[] = __sso('The Resource Owner Details URL is invalid');
  319. }
  320. }
  321. if (count($error_detected)) {
  322. foreach ($error_detected as $error) {
  323. Session::addMessageAfterRedirect(
  324. $error,
  325. true,
  326. ERROR
  327. );
  328. }
  329. return false;
  330. }
  331. if (isset($input["_blank_bgcolor"]) && $input["_blank_bgcolor"]) {
  332. $input['bgcolor'] = '';
  333. }
  334. if (isset($input["_blank_color"]) && $input["_blank_color"]) {
  335. $input['color'] = '';
  336. }
  337. if (isset($input["_blank_picture"]) && $input["_blank_picture"]) {
  338. $input['picture'] = '';
  339. if (array_key_exists('picture', $this->fields)) {
  340. PluginSinglesignonToolbox::deletePicture($this->fields['picture']);
  341. }
  342. }
  343. if (isset($input["_picture"])) {
  344. $picture = array_shift($input["_picture"]);
  345. if ($dest = PluginSinglesignonToolbox::savePicture(GLPI_TMP_DIR . '/' . $picture)) {
  346. $input['picture'] = $dest;
  347. } else {
  348. Session::addMessageAfterRedirect(__('Unable to save picture file.'), true, ERROR);
  349. }
  350. if (array_key_exists('picture', $this->fields)) {
  351. PluginSinglesignonToolbox::deletePicture($this->fields['picture']);
  352. }
  353. }
  354. return $input;
  355. }
  356. function getSearchOptions() {
  357. // For GLPI <= 9.2
  358. $options = [];
  359. foreach ($this->rawSearchOptions() as $opt) {
  360. if (!isset($opt['id'])) {
  361. continue;
  362. }
  363. $optid = $opt['id'];
  364. unset($opt['id']);
  365. if (isset($options[$optid])) {
  366. $message = "Duplicate key $optid ({$options[$optid]['name']}/{$opt['name']}) in " . get_class($this) . " searchOptions!";
  367. Toolbox::logDebug($message);
  368. }
  369. foreach ($opt as $k => $v) {
  370. $options[$optid][$k] = $v;
  371. }
  372. }
  373. return $options;
  374. }
  375. function rawSearchOptions() {
  376. $tab = [];
  377. $tab[] = [
  378. 'id' => 'common',
  379. 'name' => __('Characteristics'),
  380. ];
  381. $tab[] = [
  382. 'id' => 1,
  383. 'table' => $this->getTable(),
  384. 'field' => 'name',
  385. 'name' => __('Name'),
  386. 'datatype' => 'itemlink',
  387. ];
  388. $tab[] = [
  389. 'id' => 2,
  390. 'table' => $this->getTable(),
  391. 'field' => 'type',
  392. 'name' => __('Type'),
  393. 'searchtype' => 'equals',
  394. 'datatype' => 'specific',
  395. ];
  396. $tab[] = [
  397. 'id' => 3,
  398. 'table' => $this->getTable(),
  399. 'field' => 'client_id',
  400. 'name' => __sso('Client ID'),
  401. 'datatype' => 'text',
  402. ];
  403. $tab[] = [
  404. 'id' => 4,
  405. 'table' => $this->getTable(),
  406. 'field' => 'client_secret',
  407. 'name' => __sso('Client Secret'),
  408. 'datatype' => 'text',
  409. ];
  410. $tab[] = [
  411. 'id' => 5,
  412. 'table' => $this->getTable(),
  413. 'field' => 'scope',
  414. 'name' => __sso('Scope'),
  415. 'datatype' => 'text',
  416. ];
  417. $tab[] = [
  418. 'id' => 6,
  419. 'table' => $this->getTable(),
  420. 'field' => 'extra_options',
  421. 'name' => __sso('Extra Options'),
  422. 'datatype' => 'specific',
  423. ];
  424. $tab[] = [
  425. 'id' => 7,
  426. 'table' => $this->getTable(),
  427. 'field' => 'url_authorize',
  428. 'name' => __sso('Authorize URL'),
  429. 'datatype' => 'weblink',
  430. ];
  431. $tab[] = [
  432. 'id' => 8,
  433. 'table' => $this->getTable(),
  434. 'field' => 'url_access_token',
  435. 'name' => __sso('Access Token URL'),
  436. 'datatype' => 'weblink',
  437. ];
  438. $tab[] = [
  439. 'id' => 9,
  440. 'table' => $this->getTable(),
  441. 'field' => 'url_resource_owner_details',
  442. 'name' => __sso('Resource Owner Details URL'),
  443. 'datatype' => 'weblink',
  444. ];
  445. $tab[] = [
  446. 'id' => 10,
  447. 'table' => $this->getTable(),
  448. 'field' => 'is_active',
  449. 'name' => __('Active'),
  450. 'searchtype' => 'equals',
  451. 'datatype' => 'bool',
  452. ];
  453. $tab[] = [
  454. 'id' => 11,
  455. 'table' => $this->getTable(),
  456. 'field' => 'use_email_for_login',
  457. 'name' => __('Use email field for login'),
  458. 'searchtype' => 'equals',
  459. 'datatype' => 'bool',
  460. ];
  461. $tab[] = [
  462. 'id' => 12,
  463. 'table' => $this->getTable(),
  464. 'field' => 'split_name',
  465. 'name' => __('Split name field for First & Last Name'),
  466. 'searchtype' => 'equals',
  467. 'datatype' => 'bool',
  468. ];
  469. $tab[] = [
  470. 'id' => 30,
  471. 'table' => $this->getTable(),
  472. 'field' => 'id',
  473. 'name' => __('ID'),
  474. 'datatype' => 'itemlink',
  475. ];
  476. return $tab;
  477. }
  478. static function getSpecificValueToDisplay($field, $values, array $options = []) {
  479. if (!is_array($values)) {
  480. $values = [$field => $values];
  481. }
  482. switch ($field) {
  483. case 'type':
  484. return self::getTicketTypeName($values[$field]);
  485. case 'extra_options':
  486. return '<pre>' . $values[$field] . '</pre>';
  487. }
  488. return '';
  489. }
  490. static function getSpecificValueToSelect($field, $name = '', $values = '', array $options = []) {
  491. if (!is_array($values)) {
  492. $values = [$field => $values];
  493. }
  494. $options['display'] = false;
  495. switch ($field) {
  496. case 'type':
  497. $options['value'] = $values[$field];
  498. return self::dropdownType($name, $options);
  499. }
  500. return parent::getSpecificValueToSelect($field, $name, $values, $options);
  501. }
  502. /**
  503. * Get ticket types
  504. *
  505. * @return array of types
  506. * */
  507. static function getTypes() {
  508. $options['generic'] = __sso('Generic');
  509. $options['azure'] = __sso('Azure');
  510. $options['facebook'] = __sso('Facebook');
  511. $options['github'] = __sso('GitHub');
  512. $options['google'] = __sso('Google');
  513. $options['instagram'] = __sso('Instagram');
  514. $options['linkedin'] = __sso('LinkdeIn');
  515. return $options;
  516. }
  517. /**
  518. * Get ticket type Name
  519. *
  520. * @param $value type ID
  521. * */
  522. static function getTicketTypeName($value) {
  523. $tab = static::getTypes();
  524. // Return $value if not defined
  525. return (isset($tab[$value]) ? $tab[$value] : $value);
  526. }
  527. /**
  528. * Dropdown of ticket type
  529. *
  530. * @param $name select name
  531. * @param $options array of options:
  532. * - value : integer / preselected value (default 0)
  533. * - toadd : array / array of specific values to add at the begining
  534. * - on_change : string / value to transmit to "onChange"
  535. * - display : boolean / display or get string (default true)
  536. *
  537. * @return string id of the select
  538. * */
  539. static function dropdownType($name, $options = []) {
  540. $params['value'] = 0;
  541. $params['toadd'] = [];
  542. $params['on_change'] = '';
  543. $params['display'] = true;
  544. if (is_array($options) && count($options)) {
  545. foreach ($options as $key => $val) {
  546. $params[$key] = $val;
  547. }
  548. }
  549. $items = [];
  550. if (count($params['toadd']) > 0) {
  551. $items = $params['toadd'];
  552. }
  553. $items += self::getTypes();
  554. return Dropdown::showFromArray($name, $items, $params);
  555. }
  556. /**
  557. * Get an history entry message
  558. *
  559. * @param $data Array from glpi_logs table
  560. *
  561. * @since GLPI version 0.84
  562. *
  563. * @return string
  564. * */
  565. static function getHistoryEntry($data) {
  566. switch ($data['linked_action'] - Log::HISTORY_PLUGIN) {
  567. case 0:
  568. return __('History from plugin example', 'example');
  569. }
  570. return '';
  571. }
  572. //////////////////////////////
  573. ////// SPECIFIC MODIF MASSIVE FUNCTIONS ///////
  574. /**
  575. * @since version 0.85
  576. *
  577. * @see CommonDBTM::getSpecificMassiveActions()
  578. * */
  579. function getSpecificMassiveActions($checkitem = null) {
  580. $actions = parent::getSpecificMassiveActions($checkitem);
  581. $actions['Document_Item' . MassiveAction::CLASS_ACTION_SEPARATOR . 'add'] = _x('button', 'Add a document'); // GLPI core one
  582. $actions[__CLASS__ . MassiveAction::CLASS_ACTION_SEPARATOR . 'do_nothing'] = __('Do Nothing - just for fun', 'example'); // Specific one
  583. return $actions;
  584. }
  585. /**
  586. * @since version 0.85
  587. *
  588. * @see CommonDBTM::showMassiveActionsSubForm()
  589. * */
  590. static function showMassiveActionsSubForm(MassiveAction $ma) {
  591. switch ($ma->getAction()) {
  592. case 'DoIt':
  593. echo "&nbsp;<input type='hidden' name='toto' value='1'>" . Html::submit(_x('button', 'Post'), ['name' => 'massiveaction']) . " " . __('Write in item history', 'example');
  594. return true;
  595. case 'do_nothing':
  596. echo "&nbsp;" . Html::submit(_x('button', 'Post'), ['name' => 'massiveaction']) . " " . __('but do nothing :)', 'example');
  597. return true;
  598. }
  599. return parent::showMassiveActionsSubForm($ma);
  600. }
  601. /**
  602. * @since version 0.85
  603. *
  604. * @see CommonDBTM::processMassiveActionsForOneItemtype()
  605. * */
  606. static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item, array $ids) {
  607. global $DB;
  608. switch ($ma->getAction()) {
  609. case 'DoIt':
  610. if ($item->getType() == 'Computer') {
  611. Session::addMessageAfterRedirect(__("Right it is the type I want...", 'example'));
  612. Session::addMessageAfterRedirect(__('Write in item history', 'example'));
  613. $changes = [0, 'old value', 'new value'];
  614. foreach ($ids as $id) {
  615. if ($item->getFromDB($id)) {
  616. Session::addMessageAfterRedirect("- " . $item->getField("name"));
  617. Log::history($id, 'Computer', $changes, 'PluginExampleExample', Log::HISTORY_PLUGIN);
  618. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
  619. } else {
  620. // Example of ko count
  621. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
  622. }
  623. }
  624. } else {
  625. // When nothing is possible ...
  626. $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);
  627. }
  628. return;
  629. case 'do_nothing':
  630. if ($item->getType() == 'PluginExampleExample') {
  631. Session::addMessageAfterRedirect(__("Right it is the type I want...", 'example'));
  632. Session::addMessageAfterRedirect(__("But... I say I will do nothing for:", 'example'));
  633. foreach ($ids as $id) {
  634. if ($item->getFromDB($id)) {
  635. Session::addMessageAfterRedirect("- " . $item->getField("name"));
  636. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
  637. } else {
  638. // Example for noright / Maybe do it with can function is better
  639. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
  640. }
  641. }
  642. } else {
  643. $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);
  644. }
  645. return;
  646. }
  647. parent::processMassiveActionsForOneItemtype($ma, $item, $ids);
  648. }
  649. static function getIcon() {
  650. return "fas fa-user-lock";
  651. }
  652. public static function getDefault($type, $key, $default = null) {
  653. if (static::$default === null) {
  654. $content = file_get_contents(dirname(__FILE__) . '/../providers.json');
  655. static::$default = json_decode($content, true);
  656. }
  657. if (isset(static::$default[$type]) && static::$default[$type][$key]) {
  658. return static::$default[$type][$key];
  659. }
  660. return $default;
  661. }
  662. public function getClientType() {
  663. $value = "generic";
  664. if (isset($this->fields['type']) && !empty($this->fields['type'])) {
  665. $value = $this->fields['type'];
  666. }
  667. return $value;
  668. }
  669. public function getClientId() {
  670. $value = "";
  671. if (isset($this->fields['client_id']) && !empty($this->fields['client_id'])) {
  672. $value = $this->fields['client_id'];
  673. }
  674. return $value;
  675. }
  676. public function getClientSecret() {
  677. $value = "";
  678. if (isset($this->fields['client_secret']) && !empty($this->fields['client_secret'])) {
  679. $value = $this->fields['client_secret'];
  680. }
  681. return $value;
  682. }
  683. public function getScope() {
  684. $type = $this->getClientType();
  685. $value = static::getDefault($type, "scope");
  686. $fields = $this->fields;
  687. if (!isset($fields['scope']) || empty($fields['scope'])) {
  688. $fields['scope'] = $value;
  689. }
  690. $fields = Plugin::doHookFunction("sso:scope", $fields);
  691. return $fields['scope'];
  692. }
  693. public function getAuthorizeUrl() {
  694. $type = $this->getClientType();
  695. $value = static::getDefault($type, "url_authorize");
  696. $fields = $this->fields;
  697. if (!isset($fields['url_authorize']) || empty($fields['url_authorize'])) {
  698. $fields['url_authorize'] = $value;
  699. }
  700. $fields = Plugin::doHookFunction("sso:url_authorize", $fields);
  701. return $fields['url_authorize'];
  702. }
  703. public function getAccessTokenUrl() {
  704. $type = $this->getClientType();
  705. $value = static::getDefault($type, "url_access_token");
  706. $fields = $this->fields;
  707. if (!isset($fields['url_access_token']) || empty($fields['url_access_token'])) {
  708. $fields['url_access_token'] = $value;
  709. }
  710. $fields = Plugin::doHookFunction("sso:url_access_token", $fields);
  711. return $fields['url_access_token'];
  712. }
  713. public function getResourceOwnerDetailsUrl($access_token = null) {
  714. $type = $this->getClientType();
  715. $value = static::getDefault($type, "url_resource_owner_details", "");
  716. $fields = $this->fields;
  717. $fields['access_token'] = $access_token;
  718. if (!isset($fields['url_resource_owner_details']) || empty($fields['url_resource_owner_details'])) {
  719. $fields['url_resource_owner_details'] = $value;
  720. }
  721. $fields = Plugin::doHookFunction("sso:url_resource_owner_details", $fields);
  722. $url = $fields['url_resource_owner_details'];
  723. $url = str_replace("<access_token>", $access_token, $url);
  724. $url = str_replace("<appsecret_proof>", hash_hmac('sha256', $access_token, $this->getClientSecret()), $url);
  725. return $url;
  726. }
  727. /**
  728. * Get current URL without query string
  729. * @return string
  730. */
  731. private function getBaseURL() {
  732. $baseURL = "";
  733. if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
  734. $baseURL = ($_SERVER["HTTP_X_FORWARDED_PROTO"] == "https") ? "https://" : "http://";
  735. } else if (isset($_SERVER["HTTPS"])) {
  736. $baseURL = ($_SERVER["HTTPS"] == "on") ? "https://" : "http://";
  737. } else {
  738. $baseURL = "http://";
  739. }
  740. if (isset($_SERVER["HTTP_X_FORWARDED_HOST"])) {
  741. $baseURL .= $_SERVER["HTTP_X_FORWARDED_HOST"];
  742. } else if (isset($_SERVER["HTTP_X_FORWARDED_HOST"])) {
  743. $baseURL .= $_SERVER["HTTP_X_FORWARDED_HOST"];
  744. } else {
  745. $baseURL .= $_SERVER["SERVER_NAME"];
  746. }
  747. $port = $_SERVER["SERVER_PORT"];
  748. if (isset($_SERVER["HTTP_X_FORWARDED_PORT"])) {
  749. $port = $_SERVER["HTTP_X_FORWARDED_PORT"];
  750. }
  751. if ($port != "80" && $port != "443") {
  752. $baseURL .= ":" . $_SERVER["SERVER_PORT"];
  753. }
  754. return $baseURL;
  755. }
  756. /**
  757. * Get current URL without query string
  758. * @return string
  759. */
  760. private function getCurrentURL() {
  761. $currentURL = $this->getBaseURL();
  762. // $currentURL .= $_SERVER["REQUEST_URI"];
  763. // Ignore Query String
  764. if (isset($_SERVER["SCRIPT_NAME"])) {
  765. $currentURL .= $_SERVER["SCRIPT_NAME"];
  766. }
  767. if (isset($_SERVER["PATH_INFO"])) {
  768. $currentURL .= $_SERVER["PATH_INFO"];
  769. }
  770. return $currentURL;
  771. }
  772. /**
  773. *
  774. * @return boolean|string
  775. */
  776. public function checkAuthorization() {
  777. if (isset($_GET['error'])) {
  778. $error_description = isset($_GET['error_description']) ? $_GET['error_description'] : __("The action you have requested is not allowed.");
  779. Html::displayErrorAndDie(__($error_description), true);
  780. }
  781. if (!isset($_GET['code'])) {
  782. $state = Session::getNewCSRFToken();
  783. if (isset($_SESSION['redirect'])) {
  784. $state .= "&redirect=" . $_SESSION['redirect'];
  785. }
  786. $params = [
  787. 'client_id' => $this->getClientId(),
  788. 'scope' => $this->getScope(),
  789. 'state' => $state,
  790. 'response_type' => 'code',
  791. 'approval_prompt' => 'auto',
  792. 'redirect_uri' => $this->getCurrentURL(),
  793. ];
  794. $params = Plugin::doHookFunction("sso:authorize_params", $params);
  795. $url = $this->getAuthorizeUrl();
  796. $glue = strstr($url, '?') === false ? '?' : '&';
  797. $url .= $glue . http_build_query($params);
  798. header('Location: ' . $url);
  799. exit;
  800. }
  801. if (isset($_GET['state']) && is_integer(strpos($_GET['state'], "&redirect="))) {
  802. $pos_redirect = strpos($_GET['state'], "&redirect=");
  803. $state = substr($_GET['state'], 0, $pos_redirect);
  804. $_GET['state'] = substr($_GET['state'], $pos_redirect);
  805. } else {
  806. $state = isset($_GET['state']) ? $_GET['state'] : '';
  807. }
  808. // Check given state against previously stored one to mitigate CSRF attack
  809. Session::checkCSRF([
  810. '_glpi_csrf_token' => $state,
  811. ]);
  812. $this->_code = $_GET['code'];
  813. return $_GET['code'];
  814. }
  815. /**
  816. *
  817. * @return boolean|string
  818. */
  819. public function getAccessToken() {
  820. if ($this->_token !== null) {
  821. return $this->_token;
  822. }
  823. if ($this->_code === null) {
  824. return false;
  825. }
  826. $params = [
  827. 'client_id' => $this->getClientId(),
  828. 'client_secret' => $this->getClientSecret(),
  829. 'redirect_uri' => $this->getCurrentURL(),
  830. 'grant_type' => 'authorization_code',
  831. 'code' => $this->_code,
  832. ];
  833. $params = Plugin::doHookFunction("sso:access_token_params", $params);
  834. $url = $this->getAccessTokenUrl();
  835. $content = Toolbox::callCurl($url, [
  836. CURLOPT_HTTPHEADER => [
  837. "Accept: application/json",
  838. ],
  839. CURLOPT_POST => true,
  840. CURLOPT_POSTFIELDS => http_build_query($params),
  841. CURLOPT_SSL_VERIFYHOST => false,
  842. CURLOPT_SSL_VERIFYPEER => false,
  843. ]);
  844. if ($this->debug) {
  845. print_r("\ngetAccessToken:\n");
  846. }
  847. try {
  848. $data = json_decode($content, true);
  849. if ($this->debug) {
  850. print_r($data);
  851. }
  852. if (!isset($data['access_token'])) {
  853. return false;
  854. }
  855. $this->_token = $data['access_token'];
  856. } catch (\Exception $ex) {
  857. if ($this->debug) {
  858. print_r($content);
  859. }
  860. return false;
  861. }
  862. return $this->_token;
  863. }
  864. /**
  865. *
  866. * @return boolean|array
  867. */
  868. public function getResourceOwner() {
  869. if ($this->_resource_owner !== null) {
  870. return $this->_resource_owner;
  871. }
  872. $token = $this->getAccessToken();
  873. if (!$token) {
  874. return false;
  875. }
  876. $url = $this->getResourceOwnerDetailsUrl($token);
  877. $headers = [
  878. "Accept:application/json",
  879. "Authorization:Bearer $token",
  880. ];
  881. $headers = Plugin::doHookFunction("sso:resource_owner_header", $headers);
  882. $content = Toolbox::callCurl($url, [
  883. CURLOPT_HTTPHEADER => $headers,
  884. CURLOPT_SSL_VERIFYHOST => false,
  885. CURLOPT_SSL_VERIFYPEER => false,
  886. ]);
  887. if ($this->debug) {
  888. print_r("\ngetResourceOwner:\n");
  889. }
  890. try {
  891. $data = json_decode($content, true);
  892. if ($this->debug) {
  893. print_r($data);
  894. }
  895. $this->_resource_owner = $data;
  896. } catch (\Exception $ex) {
  897. if ($this->debug) {
  898. print_r($content);
  899. }
  900. return false;
  901. }
  902. if ($this->getClientType() === "linkedin") {
  903. if ($this->debug) {
  904. print_r("\nlinkedin:\n");
  905. }
  906. $email_url = "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))";
  907. $content = Toolbox::callCurl($email_url, [
  908. CURLOPT_HTTPHEADER => $headers,
  909. CURLOPT_SSL_VERIFYHOST => false,
  910. CURLOPT_SSL_VERIFYPEER => false,
  911. ]);
  912. try {
  913. $data = json_decode($content, true);
  914. if ($this->debug) {
  915. print_r($content);
  916. }
  917. $this->_resource_owner['email-address'] = $data['elements'][0]['handle~']['emailAddress'];
  918. } catch (\Exception $ex) {
  919. return false;
  920. }
  921. }
  922. return $this->_resource_owner;
  923. }
  924. public function findUser() {
  925. $resource_array = $this->getResourceOwner();
  926. if (!$resource_array) {
  927. return false;
  928. }
  929. $user = new User();
  930. //First: check linked user
  931. $id = Plugin::doHookFunction("sso:find_user", $resource_array);
  932. if (is_numeric($id) && $user->getFromDB($id)) {
  933. return $user;
  934. }
  935. $remote_id = false;
  936. $remote_id_fields = ['id', 'username', 'sub'];
  937. foreach ($remote_id_fields as $field) {
  938. if (isset($resource_array[$field]) && !empty($resource_array[$field])) {
  939. $remote_id = $resource_array[$field];
  940. break;
  941. }
  942. }
  943. if ($remote_id) {
  944. $link = new PluginSinglesignonProvider_User();
  945. $condition = "`remote_id` = '{$remote_id}' AND `plugin_singlesignon_providers_id` = {$this->fields['id']}";
  946. if (version_compare(GLPI_VERSION, '9.4', '>=')) {
  947. $condition = [$condition];
  948. }
  949. $links = $link->find($condition);
  950. if (!empty($links) && $first = reset($links)) {
  951. $id = $first['users_id'];
  952. }
  953. $remote_id;
  954. }
  955. if (is_numeric($id) && $user->getFromDB($id)) {
  956. return $user;
  957. }
  958. $split = $this->fields['split_domain'];
  959. $authorizedDomainsString = $this->fields['authorized_domains'];
  960. $authorizedDomains = [];
  961. if (isset($authorizedDomainsString)) {
  962. $authorizedDomains = explode(',', $authorizedDomainsString);
  963. }
  964. // check email first
  965. $email = false;
  966. $email_fields = ['email', 'e-mail', 'email-address', 'mail'];
  967. foreach ($email_fields as $field) {
  968. if (isset($resource_array[$field]) && is_string($resource_array[$field])) {
  969. $email = $resource_array[$field];
  970. $isAuthorized = empty($authorizedDomains);
  971. foreach ($authorizedDomains as $authorizedDomain) {
  972. if (preg_match("/{$authorizedDomain}$/i", $email)) {
  973. $isAuthorized = true;
  974. }
  975. }
  976. if (!$isAuthorized) {
  977. return false;
  978. }
  979. if ($split) {
  980. $emailSplit = explode("@", $email);
  981. $email = $emailSplit[0];
  982. }
  983. break;
  984. }
  985. }
  986. $login = false;
  987. $use_email = $this->fields['use_email_for_login'];
  988. if ($email && $use_email) {
  989. $login = $email;
  990. } else {
  991. $login_fields = ['userPrincipalName', 'login', 'username', 'id', 'name', 'displayName'];
  992. foreach ($login_fields as $field) {
  993. if (isset($resource_array[$field]) && is_string($resource_array[$field])) {
  994. $login = $resource_array[$field];
  995. $isAuthorized = empty($authorizedDomains);
  996. foreach ($authorizedDomains as $authorizedDomain) {
  997. if (preg_match("/{$authorizedDomain}$/i", $login)) {
  998. $isAuthorized = true;
  999. }
  1000. }
  1001. if (!$isAuthorized) {
  1002. return false;
  1003. }
  1004. if ($split) {
  1005. $loginSplit = explode("@", $login);
  1006. $login = $loginSplit[0];
  1007. }
  1008. break;
  1009. }
  1010. }
  1011. }
  1012. if ($login && $user->getFromDBbyName($login)) {
  1013. return $user;
  1014. }
  1015. $default_condition = '';
  1016. if (version_compare(GLPI_VERSION, '9.3', '>=')) {
  1017. $default_condition = [];
  1018. }
  1019. $bOk = true;
  1020. if ($email && $user->getFromDBbyEmail($email, $default_condition)) {
  1021. return $user;
  1022. } else {
  1023. $bOk = false;
  1024. }
  1025. // var_dump($bOk);
  1026. // die();
  1027. // If the user does not exist in the database and the provider is google
  1028. if (static::getClientType() == "google" && !$bOk) {
  1029. // Generates an api token and a personal token... probably not necessary
  1030. $tokenAPI = base_convert(hash('sha256', time() . mt_rand()), 16, 36);
  1031. $tokenPersonnel = base_convert(hash('sha256', time() . mt_rand()), 16, 36);
  1032. $realname = '';
  1033. if (isset($resource_array['family_name'])) {
  1034. $realname = $resource_array['family_name'];
  1035. }
  1036. $firstname = '';
  1037. if (isset($resource_array['given_name'])) {
  1038. $firstname = $resource_array['given_name'];
  1039. }
  1040. $useremail = $email;
  1041. if (isset($resource_array['email'])) {
  1042. $useremail = $resource_array['email'];
  1043. }
  1044. $userPost = [
  1045. 'name' => $login,
  1046. 'add' => 1,
  1047. 'realname' => $realname,
  1048. 'firstname' => $firstname,
  1049. //'picture' => $resource_array['picture'] ?? '',
  1050. 'api_token' => $tokenAPI,
  1051. 'personal_token' => $tokenPersonnel,
  1052. 'is_active' => 1
  1053. ];
  1054. $userPost['_useremails'][-1] = $useremail;
  1055. $user->add($userPost);
  1056. return $user;
  1057. }
  1058. // If the user does not exist in the database and the provider is generic (Ex: azure ad without common tenant)
  1059. if (static::getClientType() == "generic" && !$bOk) {
  1060. try {
  1061. // Generates an api token and a personal token... probably not necessary
  1062. $tokenAPI = base_convert(hash('sha256', time() . mt_rand()), 16, 36);
  1063. $tokenPersonnel = base_convert(hash('sha256', time() . mt_rand()), 16, 36);
  1064. $splitname = $this->fields['split_name'];
  1065. $firstLastArray = ($splitname) ? preg_split('/ /', $resource_array['name'], 2) : preg_split('/ /', $resource_array['displayName'], 2);
  1066. $userPost = [
  1067. 'name' => $login,
  1068. 'add' => 1,
  1069. 'realname' => $firstLastArray[1],
  1070. 'firstname' => $firstLastArray[0],
  1071. 'api_token' => $tokenAPI,
  1072. 'personal_token' => $tokenPersonnel,
  1073. 'is_active' => 1
  1074. ];
  1075. // Set the office location from Office 365 user as entity for the GLPI new user if they names match
  1076. if (isset($resource_array['officeLocation'])) {
  1077. global $DB;
  1078. foreach ($DB->request('glpi_entities') as $entity) {
  1079. if ($entity['name'] == $resource_array['officeLocation']) {
  1080. $userPost['entities_id'] = $entity['id'];
  1081. break;
  1082. }
  1083. }
  1084. }
  1085. if ($email) {
  1086. $userPost['_useremails'][-1] = $email;
  1087. }
  1088. //$user->check(-1, CREATE, $userPost);
  1089. $newID = $user->add($userPost);
  1090. // var_dump($newID);
  1091. $profils = 0;
  1092. // Verification default profiles exist in the entity
  1093. // If no default profile exists, the user will not be able to log in.
  1094. // In this case, we retrieve a profile and an entity and assign these values ​​to it.
  1095. // The administrator can change these values ​​later.
  1096. if (0 == Profile::getDefault()) {
  1097. // No default profiles
  1098. // Profile recovery and assignment
  1099. global $DB;
  1100. $datasProfiles = [];
  1101. foreach ($DB->request('glpi_profiles') as $data) {
  1102. array_push($datasProfiles, $data);
  1103. }
  1104. $datasEntities = [];
  1105. foreach ($DB->request('glpi_entities') as $data) {
  1106. array_push($datasEntities, $data);
  1107. }
  1108. if (count($datasProfiles) > 0 && count($datasEntities) > 0) {
  1109. $profils = $datasProfiles[0]['id'];
  1110. $entitie = $datasEntities[0]['id'];
  1111. $profile = new Profile_User();
  1112. $userProfile['users_id'] = intval($user->fields['id']);
  1113. $userProfile['entities_id'] = intval($entitie);
  1114. $userProfile['is_recursive'] = 0;
  1115. $userProfile['profiles_id'] = intval($profils);
  1116. $userProfile['add'] = "Ajouter";
  1117. $profile->add($userProfile);
  1118. } else {
  1119. return false;
  1120. }
  1121. }
  1122. return $user;
  1123. } catch (\Exception $ex) {
  1124. return false;
  1125. }
  1126. }
  1127. return false;
  1128. }
  1129. public function login() {
  1130. $user = $this->findUser();
  1131. if (!$user) {
  1132. return false;
  1133. }
  1134. //Create fake auth
  1135. $auth = new Auth();
  1136. $auth->user = $user;
  1137. $auth->auth_succeded = true;
  1138. $auth->extauth = 1;
  1139. $auth->user_present = 1;
  1140. $auth->user->fields['authtype'] = Auth::DB_GLPI;
  1141. Session::init($auth);
  1142. // Return false if the profile is not defined in Session::init($auth)
  1143. return $auth->auth_succeded;
  1144. }
  1145. public function linkUser($user_id) {
  1146. $user = new User();
  1147. if (!$user->getFromDB($user_id)) {
  1148. return false;
  1149. }
  1150. $resource_array = $this->getResourceOwner();
  1151. if (!$resource_array) {
  1152. return false;
  1153. }
  1154. $remote_id = false;
  1155. $id_fields = ['id', 'sub', 'username'];
  1156. foreach ($id_fields as $field) {
  1157. if (isset($resource_array[$field]) && !empty($resource_array[$field])) {
  1158. $remote_id = $resource_array[$field];
  1159. break;
  1160. }
  1161. }
  1162. if (!$remote_id) {
  1163. return false;
  1164. }
  1165. $link = new PluginSinglesignonProvider_User();
  1166. // Unlink from another user
  1167. $link->deleteByCriteria([
  1168. 'plugin_singlesignon_providers_id' => $this->fields['id'],
  1169. 'remote_id' => $remote_id,
  1170. ]);
  1171. return $link->add([
  1172. 'plugin_singlesignon_providers_id' => $this->fields['id'],
  1173. 'users_id' => $user_id,
  1174. 'remote_id' => $remote_id,
  1175. ]);
  1176. }
  1177. }