provider.class.php 27 KB

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