provider.class.php 46 KB

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