provider.class.php 41 KB

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