provider.class.php 27 KB

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