provider.class.php 24 KB

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