provider.class.php 43 KB

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