provider.class.php 47 KB

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