provider.class.php 49 KB

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