provider.class.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  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 = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? "https://" : "http://";
  560. $baseURL .= $_SERVER["SERVER_NAME"];
  561. if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
  562. $baseURL .= ":" . $_SERVER["SERVER_PORT"];
  563. }
  564. return $baseURL;
  565. }
  566. /**
  567. * Get current URL without query string
  568. * @return string
  569. */
  570. private function getCurrentURL() {
  571. $currentURL = $this->getBaseURL();
  572. // $currentURL .= $_SERVER["REQUEST_URI"];
  573. // Ignore Query String
  574. if (isset($_SERVER["SCRIPT_NAME"])) {
  575. $currentURL .= $_SERVER["SCRIPT_NAME"];
  576. }
  577. if (isset($_SERVER["PATH_INFO"])) {
  578. $currentURL .= $_SERVER["PATH_INFO"];
  579. }
  580. return $currentURL;
  581. }
  582. /**
  583. *
  584. * @return boolean|string
  585. */
  586. public function checkAuthorization() {
  587. if (isset($_GET['error'])) {
  588. $error_description = isset($_GET['error_description']) ? $_GET['error_description'] : __("The action you have requested is not allowed.");
  589. Html::displayErrorAndDie(__($error_description), true);
  590. }
  591. if (!isset($_GET['code'])) {
  592. $params = [
  593. 'client_id' => $this->getClientId(),
  594. 'scope' => $this->getScope(),
  595. 'state' => Session::getNewCSRFToken(),
  596. 'response_type' => 'code',
  597. 'approval_prompt' => 'auto',
  598. 'redirect_uri' => $this->getCurrentURL(),
  599. ];
  600. $params = Plugin::doHookFunction("sso:authorize_params", $params);
  601. $url = $this->getAuthorizeUrl();
  602. $glue = strstr($url, '?') === false ? '?' : '&';
  603. $url .= $glue . http_build_query($params);
  604. header('Location: ' . $url);
  605. exit;
  606. }
  607. // Check given state against previously stored one to mitigate CSRF attack
  608. $state = isset($_GET['state']) ? $_GET['state'] : '';
  609. Session::checkCSRF([
  610. '_glpi_csrf_token' => $state,
  611. ]);
  612. $this->_code = $_GET['code'];
  613. return $_GET['code'];
  614. }
  615. /**
  616. *
  617. * @return boolean|string
  618. */
  619. public function getAccessToken() {
  620. if ($this->_token !== null) {
  621. return $this->_token;
  622. }
  623. if ($this->_code === null) {
  624. return false;
  625. }
  626. $params = [
  627. 'client_id' => $this->getClientId(),
  628. 'client_secret' => $this->getClientSecret(),
  629. 'redirect_uri' => $this->getCurrentURL(),
  630. 'grant_type' => 'authorization_code',
  631. 'code' => $this->_code,
  632. ];
  633. $params = Plugin::doHookFunction("sso:access_token_params", $params);
  634. $url = $this->getAccessTokenUrl();
  635. $content = Toolbox::callCurl($url, [
  636. CURLOPT_HTTPHEADER => [
  637. "Accept: application/json",
  638. ],
  639. CURLOPT_POST => true,
  640. CURLOPT_POSTFIELDS => http_build_query($params),
  641. CURLOPT_SSL_VERIFYHOST => false,
  642. CURLOPT_SSL_VERIFYPEER => false,
  643. ]);
  644. try {
  645. $data = json_decode($content, true);
  646. $this->_token = $data['access_token'];
  647. } catch (\Exception $ex) {
  648. return false;
  649. }
  650. return $this->_token;
  651. }
  652. /**
  653. *
  654. * @return boolean|array
  655. */
  656. public function getResourceOwner() {
  657. if ($this->_resource_owner !== null) {
  658. return $this->_resource_owner;
  659. }
  660. $token = $this->getAccessToken();
  661. if (!$token) {
  662. return false;
  663. }
  664. $url = $this->getResourceOwnerDetailsUrl($token);
  665. $headers = [
  666. "Accept:application/json",
  667. "Authorization:Bearer $token",
  668. ];
  669. $headers = Plugin::doHookFunction("sso:resource_owner_header", $headers);
  670. $content = Toolbox::callCurl($url, [
  671. CURLOPT_HTTPHEADER => $headers,
  672. CURLOPT_SSL_VERIFYHOST => false,
  673. CURLOPT_SSL_VERIFYPEER => false,
  674. ]);
  675. try {
  676. $data = json_decode($content, true);
  677. $this->_resource_owner = $data;
  678. } catch (\Exception $ex) {
  679. return false;
  680. }
  681. if ($this->getClientType() === "linkedin") {
  682. $email_url = "https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))";
  683. $content = Toolbox::callCurl($email_url, [
  684. CURLOPT_HTTPHEADER => $headers,
  685. CURLOPT_SSL_VERIFYHOST => false,
  686. CURLOPT_SSL_VERIFYPEER => false,
  687. ]);
  688. try {
  689. $data = json_decode($content, true);
  690. $this->_resource_owner['email-address'] = $data['elements'][0]['handle~']['emailAddress'];
  691. } catch (\Exception $ex) {
  692. return false;
  693. }
  694. }
  695. return $this->_resource_owner;
  696. }
  697. public function findUser() {
  698. $resource_array = $this->getResourceOwner();
  699. if (!$resource_array) {
  700. return false;
  701. }
  702. $user = new User();
  703. //First: check linked user
  704. $id = Plugin::doHookFunction("sso:find_user", $resource_array);
  705. if (is_numeric($id) && $user->getFromDB($id)) {
  706. return $user;
  707. }
  708. $email = false;
  709. $email_fields = ['email', 'e-mail', 'email-address', 'mail'];
  710. foreach ($email_fields as $field) {
  711. if (isset($resource_array[$field]) && is_string($resource_array[$field])) {
  712. $email = $resource_array[$field];
  713. break;
  714. }
  715. }
  716. $default_condition = '';
  717. if (version_compare(GLPI_VERSION, '9.3', '>=')) {
  718. $default_condition = [];
  719. }
  720. if ($email && $user->getFromDBbyEmail($email, $default_condition)) {
  721. return $user;
  722. }
  723. $login = false;
  724. $login_fields = ['login', 'username', 'id'];
  725. foreach ($login_fields as $field) {
  726. if (isset($resource_array[$field]) && is_string($resource_array[$field])) {
  727. $login = $resource_array[$field];
  728. break;
  729. }
  730. }
  731. if ($login && $user->getFromDBbyName($login)) {
  732. return $user;
  733. }
  734. return false;
  735. }
  736. public function login() {
  737. $user = $this->findUser();
  738. if (!$user) {
  739. return false;
  740. }
  741. //Create fake auth
  742. $auth = new Auth();
  743. $auth->user = $user;
  744. $auth->auth_succeded = true;
  745. $auth->extauth = 1;
  746. $auth->user_present = $auth->user->getFromDBbyName(addslashes($user->fields['name']));
  747. $auth->user->fields['authtype'] = Auth::DB_GLPI;
  748. Session::init($auth);
  749. return $auth->auth_succeded;
  750. }
  751. /**
  752. * Generate a URL to callback
  753. * Some providers don't accept query string, it convert to PATH
  754. * @global array $CFG_GLPI
  755. * @param integer $id
  756. * @param array $query
  757. * @return string
  758. */
  759. public static function getCallbackUrl($id, $query = []) {
  760. global $CFG_GLPI;
  761. $url = $CFG_GLPI['root_doc'] . '/plugins/singlesignon/front/callback.php';
  762. $url .= "/provider/$id";
  763. if (!empty($query)) {
  764. $url .= "/q/" . base64_encode(http_build_query($query));
  765. }
  766. return $url;
  767. }
  768. public static function getCallbackParameters($name = null) {
  769. $data = [];
  770. if (isset($_SERVER['PATH_INFO'])) {
  771. $path_info = trim($_SERVER['PATH_INFO'], '/');
  772. $parts = explode('/', $path_info);
  773. $key = null;
  774. foreach ($parts as $part) {
  775. if ($key === null) {
  776. $key = $part;
  777. } else {
  778. if ($key === "provider" || $key === "test") {
  779. $part = intval($part);
  780. } else {
  781. $tmp = base64_decode($part);
  782. parse_str($tmp, $part);
  783. }
  784. if ($key === $name) {
  785. return $part;
  786. }
  787. $data[$key] = $part;
  788. $key = null;
  789. }
  790. }
  791. }
  792. if (!isset($data[$name])) {
  793. return null;
  794. }
  795. return $data;
  796. }
  797. }