provider.class.php 49 KB

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