provider.class.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  1. <?php
  2. class PluginSinglesignonProvider extends CommonDBTM {
  3. // From CommonDBTM
  4. public $dohistory = true;
  5. static $rightname = 'config';
  6. /**
  7. * @var array
  8. */
  9. static $default = null;
  10. /**
  11. *
  12. * @var string
  13. */
  14. protected $_code = null;
  15. /**
  16. *
  17. * @var null|string
  18. */
  19. protected $_token = null;
  20. /**
  21. *
  22. * @var null|array
  23. */
  24. protected $_resource_owner = null;
  25. public static function canCreate() {
  26. return static::canUpdate();
  27. }
  28. public static function canDelete() {
  29. return static::canUpdate();
  30. }
  31. public static function canPurge() {
  32. return static::canUpdate();
  33. }
  34. public static function canView() {
  35. return static::canUpdate();
  36. }
  37. // Should return the localized name of the type
  38. static function getTypeName($nb = 0) {
  39. return __sso('Single Sign-on Provider');
  40. }
  41. /**
  42. * @see CommonGLPI::getMenuName()
  43. * */
  44. static function getMenuName() {
  45. return __sso('Single Sign-on');
  46. }
  47. function defineTabs($options = []) {
  48. $ong = [];
  49. $this->addDefaultFormTab($ong);
  50. $this->addStandardTab(__CLASS__, $ong, $options);
  51. $this->addStandardTab('Log', $ong, $options);
  52. return $ong;
  53. }
  54. function post_getEmpty() {
  55. $this->fields["type"] = 'generic';
  56. $this->fields["is_active"] = 1;
  57. }
  58. function showForm($ID, $options = []) {
  59. global $CFG_GLPI;
  60. $this->initForm($ID, $options);
  61. $this->showFormHeader($options);
  62. if (empty($this->fields["type"])) {
  63. $this->fields["type"] = 'generic';
  64. }
  65. echo "<tr class='tab_bg_1'>";
  66. echo "<td>" . __('Name') . "</td>";
  67. echo "<td>";
  68. Html::autocompletionTextField($this, "name");
  69. echo "</td>";
  70. echo "<td>" . __('Comments') . "</td>";
  71. echo "<td>";
  72. echo "<textarea name='comment' >" . $this->fields["comment"] . "</textarea>";
  73. echo "</td></tr>";
  74. $on_change = 'var _value = this.options[this.selectedIndex].value; $(".sso_url").toggle(_value == "generic");';
  75. echo "<tr class='tab_bg_1'>";
  76. echo "<td>" . __sso('SSO Type') . "</td><td>";
  77. self::dropdownType('type', ['value' => $this->fields["type"], 'on_change' => $on_change]);
  78. echo "<td>" . __('Active') . "</td>";
  79. echo "<td>";
  80. Dropdown::showYesNo("is_active", $this->fields["is_active"]);
  81. echo "</td></tr>\n";
  82. echo "<tr class='tab_bg_1'>";
  83. echo "<td>" . __sso('Client ID') . "</td>";
  84. echo "<td><input type='text' style='width:96%' name='client_id' value='" . $this->fields["client_id"] . "'></td>";
  85. echo "<td>" . __sso('Client Secret') . "</td>";
  86. echo "<td><input type='text' style='width:96%' name='client_secret' value='" . $this->fields["client_secret"] . "'></td>";
  87. echo "</tr>\n";
  88. echo "<tr class='tab_bg_1'>";
  89. echo "<td>" . __sso('Scope') . "</td>";
  90. echo "<td><input type='text' style='width:96%' name='scope' value='" . $this->fields["scope"] . "'></td>";
  91. echo "<td>" . __sso('Extra Options') . "</td>";
  92. echo "<td><input type='text' style='width:96%' name='extra_options' value='" . $this->fields["extra_options"] . "'></td>";
  93. echo "</tr>\n";
  94. $url_style = "";
  95. if ($this->fields["type"] != 'generic') {
  96. $url_style = 'style="display: none;"';
  97. }
  98. echo "<tr class='tab_bg_1 sso_url' $url_style>";
  99. echo "<td>" . __sso('Authorize URL') . "</td>";
  100. echo "<td colspan='3'><input type='text' style='width:96%' name='url_authorize' value='" . $this->fields["url_authorize"] . "'></td>";
  101. echo "</tr>\n";
  102. echo "<tr class='tab_bg_1 sso_url' $url_style>";
  103. echo "<td>" . __sso('Access Token URL') . "</td>";
  104. echo "<td colspan='3'><input type='text' style='width:96%' name='url_access_token' value='" . $this->fields["url_access_token"] . "'></td>";
  105. echo "</tr>\n";
  106. echo "<tr class='tab_bg_1 sso_url' $url_style>";
  107. echo "<td>" . __sso('Resource Owner Details URL') . "</td>";
  108. echo "<td colspan='3'><input type='text' style='width:96%' name='url_resource_owner_details' value='" . $this->fields["url_resource_owner_details"] . "'></td>";
  109. echo "</tr>\n";
  110. if ($ID) {
  111. $url = self::getCallbackUrl($ID);
  112. $fullUrl = $this->getBaseURL() . $url;
  113. echo "<tr class='tab_bg_1'>";
  114. echo "<td>" . __sso('Callback URL') . "</td>";
  115. echo "<td colspan='3'><a id='singlesignon_callbackurl' href='$fullUrl' data-url='$url'>$fullUrl</a></td>";
  116. echo "</tr>\n";
  117. $options['addbuttons'] = ['test_singlesignon' => __sso('Test Single Sign-on')];
  118. }
  119. $this->showFormButtons($options);
  120. if ($ID) {
  121. echo '<script type="text/javascript">
  122. $("[name=test_singlesignon]").on("click", function (e) {
  123. e.preventDefault();
  124. var url = $("#singlesignon_callbackurl").attr("data-url") + "/test/1";
  125. var left = ($(window).width()/2)-(600/2);
  126. var top = ($(window).height()/2)-(800/2);
  127. var newWindow = window.open(url, "singlesignon", "width=600,height=800,left=" + left + ",top=" + top);
  128. if (window.focus) {
  129. newWindow.focus();
  130. }
  131. });
  132. </script>';
  133. }
  134. return true;
  135. }
  136. function prepareInputForAdd($input) {
  137. return $this->prepareInput($input);
  138. }
  139. function prepareInputForUpdate($input) {
  140. return $this->prepareInput($input);
  141. }
  142. /**
  143. * Prepares input (for update and add)
  144. *
  145. * @param array $input Input data
  146. *
  147. * @return array
  148. */
  149. private function prepareInput($input) {
  150. $error_detected = [];
  151. $type = '';
  152. //check for requirements
  153. if (isset($input['type'])) {
  154. $type = $input['type'];
  155. }
  156. if (!isset($input['name']) || empty($input['name'])) {
  157. $error_detected[] = __sso('A Name is required');
  158. }
  159. if (empty($type)) {
  160. $error_detected[] = __('An item type is required');
  161. } else if (!isset(static::getTypes()[$type])) {
  162. $error_detected[] = sprintf(__sso('The "%s" is a Invalid type'), $type);
  163. }
  164. if (!isset($input['client_id']) || empty($input['client_id'])) {
  165. $error_detected[] = __sso('A Client ID is required');
  166. }
  167. if (!isset($input['client_secret']) || empty($input['client_secret'])) {
  168. $error_detected[] = __sso('A Client Secret is required');
  169. }
  170. if ($type === 'generic') {
  171. if (!isset($input['url_authorize']) || empty($input['url_authorize'])) {
  172. $error_detected[] = __sso('An Authorize URL is required');
  173. } else if (!filter_var($input['url_authorize'], FILTER_VALIDATE_URL)) {
  174. $error_detected[] = __sso('The Authorize URL is invalid');
  175. }
  176. if (!isset($input['url_access_token']) || empty($input['url_access_token'])) {
  177. $error_detected[] = __sso('An Access Token URL is required');
  178. } else if (!filter_var($input['url_access_token'], FILTER_VALIDATE_URL)) {
  179. $error_detected[] = __sso('The Access Token URL is invalid');
  180. }
  181. if (!isset($input['url_resource_owner_details']) || empty($input['url_resource_owner_details'])) {
  182. $error_detected[] = __sso('A Resource Owner Details URL is required');
  183. } else if (!filter_var($input['url_resource_owner_details'], FILTER_VALIDATE_URL)) {
  184. $error_detected[] = __sso('The Resource Owner Details URL is invalid');
  185. }
  186. }
  187. if (count($error_detected)) {
  188. foreach ($error_detected as $error) {
  189. Session::addMessageAfterRedirect(
  190. $error,
  191. true,
  192. ERROR
  193. );
  194. }
  195. return false;
  196. }
  197. return $input;
  198. }
  199. function getSearchOptions() {
  200. // For GLPI <= 9.2
  201. $options = [];
  202. foreach ($this->rawSearchOptions() as $opt) {
  203. if (!isset($opt['id'])) {
  204. continue;
  205. }
  206. $optid = $opt['id'];
  207. unset($opt['id']);
  208. if (isset($options[$optid])) {
  209. $message = "Duplicate key $optid ({$options[$optid]['name']}/{$opt['name']}) in " .
  210. get_class($this) . " searchOptions!";
  211. Toolbox::logDebug($message);
  212. }
  213. foreach ($opt as $k => $v) {
  214. $options[$optid][$k] = $v;
  215. }
  216. }
  217. return $options;
  218. }
  219. function rawSearchOptions() {
  220. $tab = [];
  221. $tab[] = [
  222. 'id' => 'common',
  223. 'name' => __('Characteristics'),
  224. ];
  225. $tab[] = [
  226. 'id' => 1,
  227. 'table' => $this->getTable(),
  228. 'field' => 'name',
  229. 'name' => __('Name'),
  230. 'datatype' => 'itemlink',
  231. ];
  232. $tab[] = [
  233. 'id' => 2,
  234. 'table' => $this->getTable(),
  235. 'field' => 'type',
  236. 'name' => __('Type'),
  237. 'searchtype' => 'equals',
  238. 'datatype' => 'specific',
  239. ];
  240. $tab[] = [
  241. 'id' => 3,
  242. 'table' => $this->getTable(),
  243. 'field' => 'client_id',
  244. 'name' => __sso('Client ID'),
  245. 'datatype' => 'text',
  246. ];
  247. $tab[] = [
  248. 'id' => 4,
  249. 'table' => $this->getTable(),
  250. 'field' => 'client_secret',
  251. 'name' => __sso('Client Secret'),
  252. 'datatype' => 'text',
  253. ];
  254. $tab[] = [
  255. 'id' => 5,
  256. 'table' => $this->getTable(),
  257. 'field' => 'scope',
  258. 'name' => __sso('Scope'),
  259. 'datatype' => 'text',
  260. ];
  261. $tab[] = [
  262. 'id' => 6,
  263. 'table' => $this->getTable(),
  264. 'field' => 'extra_options',
  265. 'name' => __sso('Extra Options'),
  266. 'datatype' => 'specific',
  267. ];
  268. $tab[] = [
  269. 'id' => 7,
  270. 'table' => $this->getTable(),
  271. 'field' => 'url_authorize',
  272. 'name' => __sso('Authorize URL'),
  273. 'datatype' => 'weblink',
  274. ];
  275. $tab[] = [
  276. 'id' => 8,
  277. 'table' => $this->getTable(),
  278. 'field' => 'url_access_token',
  279. 'name' => __sso('Access Token URL'),
  280. 'datatype' => 'weblink',
  281. ];
  282. $tab[] = [
  283. 'id' => 9,
  284. 'table' => $this->getTable(),
  285. 'field' => 'url_resource_owner_details',
  286. 'name' => __sso('Resource Owner Details URL'),
  287. 'datatype' => 'weblink',
  288. ];
  289. $tab[] = [
  290. 'id' => 10,
  291. 'table' => $this->getTable(),
  292. 'field' => 'is_active',
  293. 'name' => __('Active'),
  294. 'searchtype' => 'equals',
  295. 'datatype' => 'bool',
  296. ];
  297. $tab[] = [
  298. 'id' => 30,
  299. 'table' => $this->getTable(),
  300. 'field' => 'id',
  301. 'name' => __('ID'),
  302. 'datatype' => 'itemlink',
  303. ];
  304. return $tab;
  305. }
  306. static function getSpecificValueToDisplay($field, $values, array $options = []) {
  307. if (!is_array($values)) {
  308. $values = [$field => $values];
  309. }
  310. switch ($field) {
  311. case 'type':
  312. return self::getTicketTypeName($values[$field]);
  313. case 'extra_options':
  314. return '<pre>' . $values[$field] . '</pre>';
  315. }
  316. return '';
  317. }
  318. static function getSpecificValueToSelect($field, $name = '', $values = '', array $options = []) {
  319. if (!is_array($values)) {
  320. $values = [$field => $values];
  321. }
  322. $options['display'] = false;
  323. switch ($field) {
  324. case 'type':
  325. $options['value'] = $values[$field];
  326. return self::dropdownType($name, $options);
  327. }
  328. return parent::getSpecificValueToSelect($field, $name, $values, $options);
  329. }
  330. /**
  331. * Get ticket types
  332. *
  333. * @return array of types
  334. * */
  335. static function getTypes() {
  336. $options['generic'] = __sso('Generic');
  337. $options['facebook'] = __sso('Facebook');
  338. $options['github'] = __sso('GitHub');
  339. $options['google'] = __sso('Google');
  340. $options['instagram'] = __sso('Instagram');
  341. $options['linkedin'] = __sso('LinkdeIn');
  342. return $options;
  343. }
  344. /**
  345. * Get ticket type Name
  346. *
  347. * @param $value type ID
  348. * */
  349. static function getTicketTypeName($value) {
  350. $tab = static::getTypes();
  351. // Return $value if not defined
  352. return (isset($tab[$value]) ? $tab[$value] : $value);
  353. }
  354. /**
  355. * Dropdown of ticket type
  356. *
  357. * @param $name select name
  358. * @param $options array of options:
  359. * - value : integer / preselected value (default 0)
  360. * - toadd : array / array of specific values to add at the begining
  361. * - on_change : string / value to transmit to "onChange"
  362. * - display : boolean / display or get string (default true)
  363. *
  364. * @return string id of the select
  365. * */
  366. static function dropdownType($name, $options = []) {
  367. $params['value'] = 0;
  368. $params['toadd'] = [];
  369. $params['on_change'] = '';
  370. $params['display'] = true;
  371. if (is_array($options) && count($options)) {
  372. foreach ($options as $key => $val) {
  373. $params[$key] = $val;
  374. }
  375. }
  376. $items = [];
  377. if (count($params['toadd']) > 0) {
  378. $items = $params['toadd'];
  379. }
  380. $items += self::getTypes();
  381. return Dropdown::showFromArray($name, $items, $params);
  382. }
  383. /**
  384. * Get an history entry message
  385. *
  386. * @param $data Array from glpi_logs table
  387. *
  388. * @since GLPI version 0.84
  389. *
  390. * @return string
  391. * */
  392. static function getHistoryEntry($data) {
  393. switch ($data['linked_action'] - Log::HISTORY_PLUGIN) {
  394. case 0:
  395. return __('History from plugin example', 'example');
  396. }
  397. return '';
  398. }
  399. //////////////////////////////
  400. ////// SPECIFIC MODIF MASSIVE FUNCTIONS ///////
  401. /**
  402. * @since version 0.85
  403. *
  404. * @see CommonDBTM::getSpecificMassiveActions()
  405. * */
  406. function getSpecificMassiveActions($checkitem = null) {
  407. $actions = parent::getSpecificMassiveActions($checkitem);
  408. $actions['Document_Item' . MassiveAction::CLASS_ACTION_SEPARATOR . 'add'] = _x('button', 'Add a document'); // GLPI core one
  409. $actions[__CLASS__ . MassiveAction::CLASS_ACTION_SEPARATOR . 'do_nothing'] = __('Do Nothing - just for fun', 'example'); // Specific one
  410. return $actions;
  411. }
  412. /**
  413. * @since version 0.85
  414. *
  415. * @see CommonDBTM::showMassiveActionsSubForm()
  416. * */
  417. static function showMassiveActionsSubForm(MassiveAction $ma) {
  418. switch ($ma->getAction()) {
  419. case 'DoIt':
  420. echo "&nbsp;<input type='hidden' name='toto' value='1'>" .
  421. Html::submit(_x('button', 'Post'), ['name' => 'massiveaction']) .
  422. " " . __('Write in item history', 'example');
  423. return true;
  424. case 'do_nothing' :
  425. echo "&nbsp;" . Html::submit(_x('button', 'Post'), ['name' => 'massiveaction']) .
  426. " " . __('but do nothing :)', 'example');
  427. return true;
  428. }
  429. return parent::showMassiveActionsSubForm($ma);
  430. }
  431. /**
  432. * @since version 0.85
  433. *
  434. * @see CommonDBTM::processMassiveActionsForOneItemtype()
  435. * */
  436. static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item, array $ids) {
  437. global $DB;
  438. switch ($ma->getAction()) {
  439. case 'DoIt' :
  440. if ($item->getType() == 'Computer') {
  441. Session::addMessageAfterRedirect(__("Right it is the type I want...", 'example'));
  442. Session::addMessageAfterRedirect(__('Write in item history', 'example'));
  443. $changes = [0, 'old value', 'new value'];
  444. foreach ($ids as $id) {
  445. if ($item->getFromDB($id)) {
  446. Session::addMessageAfterRedirect("- " . $item->getField("name"));
  447. Log::history($id, 'Computer', $changes, 'PluginExampleExample', Log::HISTORY_PLUGIN);
  448. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
  449. } else {
  450. // Example of ko count
  451. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
  452. }
  453. }
  454. } else {
  455. // When nothing is possible ...
  456. $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);
  457. }
  458. return;
  459. case 'do_nothing' :
  460. If ($item->getType() == 'PluginExampleExample') {
  461. Session::addMessageAfterRedirect(__("Right it is the type I want...", 'example'));
  462. Session::addMessageAfterRedirect(__("But... I say I will do nothing for:", 'example'));
  463. foreach ($ids as $id) {
  464. if ($item->getFromDB($id)) {
  465. Session::addMessageAfterRedirect("- " . $item->getField("name"));
  466. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
  467. } else {
  468. // Example for noright / Maybe do it with can function is better
  469. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
  470. }
  471. }
  472. } else {
  473. $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);
  474. }
  475. Return;
  476. }
  477. parent::processMassiveActionsForOneItemtype($ma, $item, $ids);
  478. }
  479. public static function getDefault($type, $key, $default = null) {
  480. if (static::$default === null) {
  481. $content = file_get_contents(dirname(__FILE__) . '/../providers.json');
  482. static::$default = json_decode($content, true);
  483. }
  484. if (isset(static::$default[$type]) && static::$default[$type][$key]) {
  485. return static::$default[$type][$key];
  486. }
  487. return $default;
  488. }
  489. public function getClientType() {
  490. $value = "generic";
  491. if (isset($this->fields['type']) && !empty($this->fields['type'])) {
  492. $value = $this->fields['type'];
  493. }
  494. return $value;
  495. }
  496. public function getClientId() {
  497. $value = "";
  498. if (isset($this->fields['client_id']) && !empty($this->fields['client_id'])) {
  499. $value = $this->fields['client_id'];
  500. }
  501. return $value;
  502. }
  503. public function getClientSecret() {
  504. $value = "";
  505. if (isset($this->fields['client_secret']) && !empty($this->fields['client_secret'])) {
  506. $value = $this->fields['client_secret'];
  507. }
  508. return $value;
  509. }
  510. public function getScope() {
  511. $type = $this->getClientType();
  512. $value = static::getDefault($type, "scope");
  513. $fields = $this->fields;
  514. if (!isset($fields['scope']) || empty($fields['scope'])) {
  515. $fields['scope'] = $value;
  516. }
  517. $fields = Plugin::doHookFunction("sso:scope", $fields);
  518. return $fields['scope'];
  519. }
  520. public function getAuthorizeUrl() {
  521. $type = $this->getClientType();
  522. $value = static::getDefault($type, "url_authorize");
  523. $fields = $this->fields;
  524. if (!isset($fields['url_authorize']) || empty($fields['url_authorize'])) {
  525. $fields['url_authorize'] = $value;
  526. }
  527. $fields = Plugin::doHookFunction("sso:url_authorize", $fields);
  528. return $fields['url_authorize'];
  529. }
  530. public function getAccessTokenUrl() {
  531. $type = $this->getClientType();
  532. $value = static::getDefault($type, "url_access_token");
  533. $fields = $this->fields;
  534. if (!isset($fields['url_access_token']) || empty($fields['url_access_token'])) {
  535. $fields['url_access_token'] = $value;
  536. }
  537. $fields = Plugin::doHookFunction("sso:url_access_token", $fields);
  538. return $fields['url_access_token'];
  539. }
  540. public function getResourceOwnerDetailsUrl($access_token) {
  541. $type = $this->getClientType();
  542. $value = static::getDefault($type, "url_resource_owner_details", "");
  543. $fields = $this->fields;
  544. $fields['access_token'] = $access_token;
  545. if (!isset($fields['url_resource_owner_details']) || empty($fields['url_resource_owner_details'])) {
  546. $fields['url_resource_owner_details'] = $value;
  547. }
  548. $fields = Plugin::doHookFunction("sso:url_resource_owner_details", $fields);
  549. $url = $fields['url_resource_owner_details'];
  550. $url = str_replace("<access_token>", $access_token, $url);
  551. $url = str_replace("<appsecret_proof>", hash_hmac('sha256', $access_token, $this->getClientSecret()), $url);
  552. return $url;
  553. }
  554. /**
  555. * Get current URL without query string
  556. * @return string
  557. */
  558. private function getBaseURL() {
  559. $baseURL = "";
  560. if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
  561. $baseURL = ($_SERVER["HTTP_X_FORWARDED_PROTO"] == "https") ? "https://" : "http://";
  562. } else if (isset($_SERVER["HTTPS"])) {
  563. $baseURL = ($_SERVER["HTTPS"] == "on") ? "https://" : "http://";
  564. } else {
  565. $baseURL = "http://";
  566. }
  567. if (isset($_SERVER["HTTP_X_FORWARDED_HOST"])) {
  568. $baseURL .= $_SERVER["HTTP_X_FORWARDED_HOST"];
  569. } else if (isset($_SERVER["HTTP_X_FORWARDED_HOST"])) {
  570. $baseURL .= $_SERVER["HTTP_X_FORWARDED_HOST"];
  571. } else {
  572. $baseURL .= $_SERVER["SERVER_NAME"];
  573. }
  574. $port = $_SERVER["SERVER_PORT"];
  575. if (isset($_SERVER["HTTP_X_FORWARDED_PORT"])) {
  576. $port = $_SERVER["HTTP_X_FORWARDED_PORT"];
  577. }
  578. if ($port != "80" && $port != "443") {
  579. $baseURL .= ":" . $_SERVER["SERVER_PORT"];
  580. }
  581. return $baseURL;
  582. }
  583. /**
  584. * Get current URL without query string
  585. * @return string
  586. */
  587. private function getCurrentURL() {
  588. $currentURL = $this->getBaseURL();
  589. // $currentURL .= $_SERVER["REQUEST_URI"];
  590. // Ignore Query String
  591. if (isset($_SERVER["SCRIPT_NAME"])) {
  592. $currentURL .= $_SERVER["SCRIPT_NAME"];
  593. }
  594. if (isset($_SERVER["PATH_INFO"])) {
  595. $currentURL .= $_SERVER["PATH_INFO"];
  596. }
  597. return $currentURL;
  598. }
  599. /**
  600. *
  601. * @return boolean|string
  602. */
  603. public function checkAuthorization() {
  604. if (isset($_GET['error'])) {
  605. $error_description = isset($_GET['error_description']) ? $_GET['error_description'] : __("The action you have requested is not allowed.");
  606. Html::displayErrorAndDie(__($error_description), true);
  607. }
  608. if (!isset($_GET['code'])) {
  609. $params = [
  610. 'client_id' => $this->getClientId(),
  611. 'scope' => $this->getScope(),
  612. 'state' => Session::getNewCSRFToken(),
  613. 'response_type' => 'code',
  614. 'approval_prompt' => 'auto',
  615. 'redirect_uri' => $this->getCurrentURL(),
  616. ];
  617. $params = Plugin::doHookFunction("sso:authorize_params", $params);
  618. $url = $this->getAuthorizeUrl();
  619. $glue = strstr($url, '?') === false ? '?' : '&';
  620. $url .= $glue . http_build_query($params);
  621. header('Location: ' . $url);
  622. exit;
  623. }
  624. // Check given state against previously stored one to mitigate CSRF attack
  625. $state = isset($_GET['state']) ? $_GET['state'] : '';
  626. Session::checkCSRF([
  627. '_glpi_csrf_token' => $state,
  628. ]);
  629. $this->_code = $_GET['code'];
  630. return $_GET['code'];
  631. }
  632. /**
  633. *
  634. * @return boolean|string
  635. */
  636. public function getAccessToken() {
  637. if ($this->_token !== null) {
  638. return $this->_token;
  639. }
  640. if ($this->_code === null) {
  641. return false;
  642. }
  643. $params = [
  644. 'client_id' => $this->getClientId(),
  645. 'client_secret' => $this->getClientSecret(),
  646. 'redirect_uri' => $this->getCurrentURL(),
  647. 'grant_type' => 'authorization_code',
  648. 'code' => $this->_code,
  649. ];
  650. $params = Plugin::doHookFunction("sso:access_token_params", $params);
  651. $url = $this->getAccessTokenUrl();
  652. $content = Toolbox::callCurl($url, [
  653. CURLOPT_HTTPHEADER => [
  654. "Accept: application/json",
  655. ],
  656. CURLOPT_POST => true,
  657. CURLOPT_POSTFIELDS => http_build_query($params),
  658. CURLOPT_SSL_VERIFYHOST => false,
  659. CURLOPT_SSL_VERIFYPEER => false,
  660. ]);
  661. try {
  662. $data = json_decode($content, true);
  663. if (!isset($data['access_token'])) {
  664. return false;
  665. }
  666. $this->_token = $data['access_token'];
  667. } catch (\Exception $ex) {
  668. return false;
  669. }
  670. return $this->_token;
  671. }
  672. /**
  673. *
  674. * @return boolean|array
  675. */
  676. public function getResourceOwner() {
  677. if ($this->_resource_owner !== null) {
  678. return $this->_resource_owner;
  679. }
  680. $token = $this->getAccessToken();
  681. if (!$token) {
  682. return false;
  683. }
  684. $url = $this->getResourceOwnerDetailsUrl($token);
  685. $headers = [
  686. "Accept:application/json",
  687. "Authorization:Bearer $token",
  688. ];
  689. $headers = Plugin::doHookFunction("sso:resource_owner_header", $headers);
  690. $content = Toolbox::callCurl($url, [
  691. CURLOPT_HTTPHEADER => $headers,
  692. CURLOPT_SSL_VERIFYHOST => false,
  693. CURLOPT_SSL_VERIFYPEER => false,
  694. ]);
  695. try {
  696. $data = json_decode($content, true);
  697. $this->_resource_owner = $data;
  698. } catch (\Exception $ex) {
  699. return false;
  700. }
  701. if ($this->getClientType() === "linkedin") {
  702. $email_url = "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))";
  703. $content = Toolbox::callCurl($email_url, [
  704. CURLOPT_HTTPHEADER => $headers,
  705. CURLOPT_SSL_VERIFYHOST => false,
  706. CURLOPT_SSL_VERIFYPEER => false,
  707. ]);
  708. try {
  709. $data = json_decode($content, true);
  710. $this->_resource_owner['email-address'] = $data['elements'][0]['handle~']['emailAddress'];
  711. } catch (\Exception $ex) {
  712. return false;
  713. }
  714. }
  715. return $this->_resource_owner;
  716. }
  717. public function findUser() {
  718. $resource_array = $this->getResourceOwner();
  719. if (!$resource_array) {
  720. return false;
  721. }
  722. $user = new User();
  723. //First: check linked user
  724. $id = Plugin::doHookFunction("sso:find_user", $resource_array);
  725. if (is_numeric($id) && $user->getFromDB($id)) {
  726. return $user;
  727. }
  728. $email = false;
  729. $email_fields = ['email', 'e-mail', 'email-address', 'mail'];
  730. foreach ($email_fields as $field) {
  731. if (isset($resource_array[$field]) && is_string($resource_array[$field])) {
  732. $email = $resource_array[$field];
  733. break;
  734. }
  735. }
  736. $default_condition = '';
  737. if (version_compare(GLPI_VERSION, '9.3', '>=')) {
  738. $default_condition = [];
  739. }
  740. if ($email && $user->getFromDBbyEmail($email, $default_condition)) {
  741. return $user;
  742. }
  743. $login = false;
  744. $login_fields = ['login', 'username', 'id'];
  745. foreach ($login_fields as $field) {
  746. if (isset($resource_array[$field]) && is_string($resource_array[$field])) {
  747. $login = $resource_array[$field];
  748. break;
  749. }
  750. }
  751. if ($login && $user->getFromDBbyName($login)) {
  752. return $user;
  753. }
  754. return false;
  755. }
  756. public function login() {
  757. $user = $this->findUser();
  758. if (!$user) {
  759. return false;
  760. }
  761. //Create fake auth
  762. $auth = new Auth();
  763. $auth->user = $user;
  764. $auth->auth_succeded = true;
  765. $auth->extauth = 1;
  766. $auth->user_present = $auth->user->getFromDBbyName(addslashes($user->fields['name']));
  767. $auth->user->fields['authtype'] = Auth::DB_GLPI;
  768. Session::init($auth);
  769. return $auth->auth_succeded;
  770. }
  771. /**
  772. * Generate a URL to callback
  773. * Some providers don't accept query string, it convert to PATH
  774. * @global array $CFG_GLPI
  775. * @param integer $id
  776. * @param array $query
  777. * @return string
  778. */
  779. public static function getCallbackUrl($id, $query = []) {
  780. global $CFG_GLPI;
  781. $url = $CFG_GLPI['root_doc'] . '/plugins/singlesignon/front/callback.php';
  782. $url .= "/provider/$id";
  783. if (!empty($query)) {
  784. $url .= "/q/" . base64_encode(http_build_query($query));
  785. }
  786. return $url;
  787. }
  788. public static function getCallbackParameters($name = null) {
  789. $data = [];
  790. if (isset($_SERVER['PATH_INFO'])) {
  791. $path_info = trim($_SERVER['PATH_INFO'], '/');
  792. $parts = explode('/', $path_info);
  793. $key = null;
  794. foreach ($parts as $part) {
  795. if ($key === null) {
  796. $key = $part;
  797. } else {
  798. if ($key === "provider" || $key === "test") {
  799. $part = intval($part);
  800. } else {
  801. $tmp = base64_decode($part);
  802. parse_str($tmp, $part);
  803. }
  804. if ($key === $name) {
  805. return $part;
  806. }
  807. $data[$key] = $part;
  808. $key = null;
  809. }
  810. }
  811. }
  812. if (!isset($data[$name])) {
  813. return null;
  814. }
  815. return $data;
  816. }
  817. }