provider.class.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. <?php
  2. class PluginSinglesignonProvider extends CommonDBTM {
  3. static $rightname = 'config';
  4. /**
  5. * Provider instance
  6. * @var null|\League\OAuth2\Client\Provider\GenericProvider
  7. */
  8. protected $_provider = null;
  9. protected $_code = null;
  10. /**
  11. *
  12. * @var null|\League\OAuth2\Client\Token\AccessToken
  13. */
  14. protected $_token = null;
  15. /**
  16. *
  17. * @var null|\League\OAuth2\Client\Provider\ResourceOwnerInterface
  18. */
  19. protected $_resource_owner = null;
  20. public static function canCreate() {
  21. if (static::$rightname) {
  22. return Session::haveRight(static::$rightname, UPDATE);
  23. }
  24. return false;
  25. }
  26. // Should return the localized name of the type
  27. static function getTypeName($nb = 0) {
  28. return __sso('Single Sign-on Provider');
  29. }
  30. /**
  31. * @see CommonGLPI::getMenuName()
  32. * */
  33. static function getMenuName() {
  34. return __sso('Single Sign-on');
  35. }
  36. /**
  37. * @see CommonGLPI::getAdditionalMenuLinks()
  38. * */
  39. static function getAdditionalMenuLinks() {
  40. global $CFG_GLPI;
  41. $links = array();
  42. // $links['add'] = '/plugins/singlesignon/front/provider.form.php';
  43. // $links['config'] = '/plugins/singlesignon/index.php';
  44. $links["<img src='" . $CFG_GLPI["root_doc"] . "/pics/menu_showall.png' title='" . __s('Show all') . "' alt='" . __s('Show all') . "'>"] = '/plugins/singlesignon/index.php';
  45. $links[__s('Test link', 'singlesignon')] = '/plugins/singlesignon/index.php';
  46. return $links;
  47. }
  48. // public function maybeTemplate() {
  49. // parent::maybeTemplate();
  50. // }
  51. function defineTabs($options = array()) {
  52. $ong = array();
  53. $this->addDefaultFormTab($ong);
  54. $this->addStandardTab('Link', $ong, $options);
  55. return $ong;
  56. }
  57. function showForm($ID, $options = array()) {
  58. global $CFG_GLPI;
  59. $this->initForm($ID, $options);
  60. $this->showFormHeader($options);
  61. if (empty($this->fields["type"])) {
  62. $this->fields["type"] = 'generic';
  63. }
  64. echo "<tr class='tab_bg_1'>";
  65. echo "<td>" . __('Name') . "</td>";
  66. echo "<td>";
  67. Html::autocompletionTextField($this, "name");
  68. echo "</td>";
  69. echo "<td>" . __('Comments') . "</td>";
  70. echo "<td>";
  71. echo "<textarea name='comment' >" . $this->fields["comment"] . "</textarea>";
  72. echo "</td></tr>";
  73. $on_change = 'var _value = this.options[this.selectedIndex].value; $(".sso_url").toggle(_value == "generic");';
  74. echo "<tr class='tab_bg_1'>";
  75. echo "<td>" . __sso('SSO Type') . "</td><td>";
  76. self::dropdownType('type', array('value' => $this->fields["type"], 'on_change' => $on_change));
  77. echo "<td>" . __('Active') . "</td>";
  78. echo "<td>";
  79. Dropdown::showYesNo("is_active", $this->fields["is_active"]);
  80. echo "</td></tr>\n";
  81. echo "<tr class='tab_bg_1'>";
  82. echo "<td>" . __sso('Client ID') . "</td>";
  83. echo "<td><input type='text' style='width:96%' name='client_id' value='" . $this->fields["client_id"] . "'></td>";
  84. echo "<td>" . __sso('Client Secret') . "</td>";
  85. echo "<td><input type='text' style='width:96%' name='client_secret' value='" . $this->fields["client_secret"] . "'></td>";
  86. echo "</tr>\n";
  87. echo "<tr class='tab_bg_1'>";
  88. echo "<td>" . __sso('Scope') . "</td>";
  89. echo "<td><input type='text' style='width:96%' name='scope' value='" . $this->fields["scope"] . "'></td>";
  90. echo "<td>" . __sso('Extra Options') . "</td>";
  91. echo "<td><input type='text' style='width:96%' name='extra_options' value='" . $this->fields["extra_options"] . "'></td>";
  92. echo "</tr>\n";
  93. $url_style = "";
  94. if ($this->fields["type"] != 'generic') {
  95. $url_style = 'style="display: none;"';
  96. }
  97. echo "<tr class='tab_bg_1 sso_url' $url_style>";
  98. echo "<td>" . __sso('Authorize URL') . "</td>";
  99. echo "<td colspan='3'><input type='text' style='width:96%' name='url_authorize' value='" . $this->fields["url_authorize"] . "'></td>";
  100. echo "</tr>\n";
  101. echo "<tr class='tab_bg_1 sso_url' $url_style>";
  102. echo "<td>" . __sso('Access Token URL') . "</td>";
  103. echo "<td colspan='3'><input type='text' style='width:96%' name='url_access_token' value='" . $this->fields["url_access_token"] . "'></td>";
  104. echo "</tr>\n";
  105. echo "<tr class='tab_bg_1 sso_url' $url_style>";
  106. echo "<td>" . __sso('Resource Owner Details URL') . "</td>";
  107. echo "<td colspan='3'><input type='text' style='width:96%' name='url_resource_owner_details' value='" . $this->fields["url_resource_owner_details"] . "'></td>";
  108. echo "</tr>\n";
  109. $this->showFormButtons($options);
  110. return true;
  111. }
  112. function getSearchOptions() {
  113. $tab = array();
  114. $tab['common'] = __('Characteristics');
  115. $tab[1]['table'] = $this->getTable();
  116. $tab[1]['field'] = 'type';
  117. $tab[1]['name'] = __('Type');
  118. $tab[1]['searchtype'] = 'equals';
  119. $tab[1]['datatype'] = 'specific';
  120. $tab[2]['table'] = $this->getTable();
  121. $tab[2]['field'] = 'name';
  122. $tab[2]['name'] = __('Name');
  123. $tab[2]['datatype'] = 'text';
  124. $tab[3]['table'] = $this->getTable();
  125. $tab[3]['field'] = 'client_id';
  126. $tab[3]['name'] = __sso('Client ID');
  127. $tab[3]['datatype'] = 'text';
  128. $tab[4]['table'] = $this->getTable();
  129. $tab[4]['field'] = 'client_secret';
  130. $tab[4]['name'] = __sso('Client Secret');
  131. $tab[4]['datatype'] = 'text';
  132. $tab[5]['table'] = $this->getTable();
  133. $tab[5]['field'] = 'scope';
  134. $tab[5]['name'] = __sso('Client Secret');
  135. $tab[5]['datatype'] = 'text';
  136. $tab[6]['table'] = $this->getTable();
  137. $tab[6]['field'] = 'extra_options';
  138. $tab[6]['name'] = __sso('Extra Options');
  139. $tab[6]['datatype'] = 'text';
  140. $tab[7]['table'] = $this->getTable();
  141. $tab[7]['field'] = 'url_authorize';
  142. $tab[7]['name'] = __sso('URL Authorize');
  143. $tab[7]['datatype'] = 'weblink';
  144. $tab[8]['table'] = $this->getTable();
  145. $tab[8]['field'] = 'url_access_token';
  146. $tab[8]['name'] = __sso('URL Access Token');
  147. $tab[8]['datatype'] = 'weblink';
  148. $tab[9]['table'] = $this->getTable();
  149. $tab[9]['field'] = 'url_resource_owner_details';
  150. $tab[9]['name'] = __sso('URL Resource Owner Details');
  151. $tab[9]['datatype'] = 'weblink';
  152. $tab[10]['table'] = $this->getTable();
  153. $tab[10]['field'] = 'is_active';
  154. $tab[10]['name'] = __('Active');
  155. $tab[10]['searchtype'] = 'equals';
  156. $tab[10]['datatype'] = 'bool';
  157. $tab[30]['table'] = $this->getTable();
  158. $tab[30]['field'] = 'id';
  159. $tab[30]['name'] = __('ID');
  160. return $tab;
  161. }
  162. static function getSpecificValueToDisplay($field, $values, array $options = array()) {
  163. if (!is_array($values)) {
  164. $values = array($field => $values);
  165. }
  166. switch ($field) {
  167. case 'type':
  168. return self::getTicketTypeName($values[$field]);
  169. case 'extra_options':
  170. return '<pre>' . $values[$field] . '</pre>';
  171. }
  172. return '';
  173. }
  174. static function getSpecificValueToSelect($field, $name = '', $values = '', array $options = array()) {
  175. if (!is_array($values)) {
  176. $values = array($field => $values);
  177. }
  178. $options['display'] = false;
  179. switch ($field) {
  180. case 'type':
  181. $options['value'] = $values[$field];
  182. return self::dropdownType($name, $options);
  183. }
  184. return parent::getSpecificValueToSelect($field, $name, $values, $options);
  185. }
  186. /**
  187. * Get ticket types
  188. *
  189. * @return array of types
  190. * */
  191. static function getTypes() {
  192. $options['generic'] = __sso('Generic');
  193. $options['facebook'] = __sso('Facebook');
  194. $options['github'] = __sso('GitHub');
  195. $options['google'] = __sso('Google');
  196. $options['instagram'] = __sso('Instagram');
  197. $options['linkedin'] = __sso('LinkdeIn');
  198. return $options;
  199. }
  200. /**
  201. * Get ticket type Name
  202. *
  203. * @param $value type ID
  204. * */
  205. static function getTicketTypeName($value) {
  206. $tab = static::getTypes();
  207. // Return $value if not defined
  208. return (isset($tab[$value]) ? $tab[$value] : $value);
  209. }
  210. /**
  211. * Dropdown of ticket type
  212. *
  213. * @param $name select name
  214. * @param $options array of options:
  215. * - value : integer / preselected value (default 0)
  216. * - toadd : array / array of specific values to add at the begining
  217. * - on_change : string / value to transmit to "onChange"
  218. * - display : boolean / display or get string (default true)
  219. *
  220. * @return string id of the select
  221. * */
  222. static function dropdownType($name, $options = array()) {
  223. $params['value'] = 0;
  224. $params['toadd'] = array();
  225. $params['on_change'] = '';
  226. $params['display'] = true;
  227. if (is_array($options) && count($options)) {
  228. foreach ($options as $key => $val) {
  229. $params[$key] = $val;
  230. }
  231. }
  232. $items = array();
  233. if (count($params['toadd']) > 0) {
  234. $items = $params['toadd'];
  235. }
  236. $items += self::getTypes();
  237. return Dropdown::showFromArray($name, $items, $params);
  238. }
  239. /**
  240. * Get an history entry message
  241. *
  242. * @param $data Array from glpi_logs table
  243. *
  244. * @since GLPI version 0.84
  245. *
  246. * @return string
  247. * */
  248. static function getHistoryEntry($data) {
  249. switch ($data['linked_action'] - Log::HISTORY_PLUGIN) {
  250. case 0:
  251. return __('History from plugin example', 'example');
  252. }
  253. return '';
  254. }
  255. //////////////////////////////
  256. ////// SPECIFIC MODIF MASSIVE FUNCTIONS ///////
  257. /**
  258. * @since version 0.85
  259. *
  260. * @see CommonDBTM::getSpecificMassiveActions()
  261. * */
  262. function getSpecificMassiveActions($checkitem = null) {
  263. $actions = parent::getSpecificMassiveActions($checkitem);
  264. $actions['Document_Item' . MassiveAction::CLASS_ACTION_SEPARATOR . 'add'] = _x('button', 'Add a document'); // GLPI core one
  265. $actions[__CLASS__ . MassiveAction::CLASS_ACTION_SEPARATOR . 'do_nothing'] = __('Do Nothing - just for fun', 'example'); // Specific one
  266. return $actions;
  267. }
  268. /**
  269. * @since version 0.85
  270. *
  271. * @see CommonDBTM::showMassiveActionsSubForm()
  272. * */
  273. static function showMassiveActionsSubForm(MassiveAction $ma) {
  274. switch ($ma->getAction()) {
  275. case 'DoIt':
  276. echo "&nbsp;<input type='hidden' name='toto' value='1'>" .
  277. Html::submit(_x('button', 'Post'), array('name' => 'massiveaction')) .
  278. " " . __('Write in item history', 'example');
  279. return true;
  280. case 'do_nothing' :
  281. echo "&nbsp;" . Html::submit(_x('button', 'Post'), array('name' => 'massiveaction')) .
  282. " " . __('but do nothing :)', 'example');
  283. return true;
  284. }
  285. return parent::showMassiveActionsSubForm($ma);
  286. }
  287. /**
  288. * @since version 0.85
  289. *
  290. * @see CommonDBTM::processMassiveActionsForOneItemtype()
  291. * */
  292. static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item, array $ids) {
  293. global $DB;
  294. switch ($ma->getAction()) {
  295. case 'DoIt' :
  296. if ($item->getType() == 'Computer') {
  297. Session::addMessageAfterRedirect(__("Right it is the type I want...", 'example'));
  298. Session::addMessageAfterRedirect(__('Write in item history', 'example'));
  299. $changes = array(0, 'old value', 'new value');
  300. foreach ($ids as $id) {
  301. if ($item->getFromDB($id)) {
  302. Session::addMessageAfterRedirect("- " . $item->getField("name"));
  303. Log::history($id, 'Computer', $changes, 'PluginExampleExample', Log::HISTORY_PLUGIN);
  304. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
  305. } else {
  306. // Example of ko count
  307. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
  308. }
  309. }
  310. } else {
  311. // When nothing is possible ...
  312. $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);
  313. }
  314. return;
  315. case 'do_nothing' :
  316. If ($item->getType() == 'PluginExampleExample') {
  317. Session::addMessageAfterRedirect(__("Right it is the type I want...", 'example'));
  318. Session::addMessageAfterRedirect(__("But... I say I will do nothing for:", 'example'));
  319. foreach ($ids as $id) {
  320. if ($item->getFromDB($id)) {
  321. Session::addMessageAfterRedirect("- " . $item->getField("name"));
  322. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
  323. } else {
  324. // Example for noright / Maybe do it with can function is better
  325. $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_KO);
  326. }
  327. }
  328. } else {
  329. $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);
  330. }
  331. Return;
  332. }
  333. parent::processMassiveActionsForOneItemtype($ma, $item, $ids);
  334. }
  335. /**
  336. *
  337. * @param string $type
  338. * @param array $options
  339. * @param array $collaborators
  340. * @return \League\OAuth2\Client\Provider\AbstractProvider
  341. */
  342. public static function createInstance($type = 'generic', array $options = array(), array $collaborators = array()) {
  343. if (!isset($options['scope'])) {
  344. $options['scope'] = array();
  345. }
  346. switch ($type) {
  347. case 'facebook':
  348. if (!isset($options['graphApiVersion'])) {
  349. $options['graphApiVersion'] = 'v2.12';
  350. }
  351. return new League\OAuth2\Client\Provider\Facebook($options, $collaborators);
  352. case 'github':
  353. $options['scope'][] = 'user:email';
  354. return new League\OAuth2\Client\Provider\Github($options, $collaborators);
  355. case 'google':
  356. return new League\OAuth2\Client\Provider\Google($options, $collaborators);
  357. case 'instagram':
  358. return new League\OAuth2\Client\Provider\Instagram($options, $collaborators);
  359. case 'linkedin':
  360. $options['scope'][] = 'r_emailaddress';
  361. return new League\OAuth2\Client\Provider\LinkedIn($options, $collaborators);
  362. case 'generic':
  363. default:
  364. return new League\OAuth2\Client\Provider\GenericProvider($options, $collaborators);
  365. }
  366. }
  367. private function getCurrentURL() {
  368. $currentURL = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? "https://" : "http://";
  369. $currentURL .= $_SERVER["SERVER_NAME"];
  370. if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
  371. $currentURL .= ":" . $_SERVER["SERVER_PORT"];
  372. }
  373. $currentURL .= $_SERVER["REQUEST_URI"];
  374. return $currentURL;
  375. }
  376. public function prepareProviderInstance(array $options = array(), array $collaborators = array()) {
  377. global $CFG_GLPI;
  378. if ($this->_provider === null) {
  379. $redirect_uri = $this->getCurrentURL();
  380. $type = $this->fields['type'];
  381. $default = array(
  382. 'clientId' => $this->fields['client_id'],
  383. 'clientSecret' => $this->fields['client_secret'],
  384. 'redirectUri' => $redirect_uri,
  385. );
  386. if ($type === 'generic') {
  387. $default['urlAuthorize'] = $this->fields['url_authorize'];
  388. $default['urlAccessToken'] = $this->fields['url_accessToken'];
  389. $default['urlResourceOwnerDetails'] = $this->fields['url_resource_owner_details'];
  390. }
  391. if (!empty($this->fields['extra_options'])) {
  392. try {
  393. $extra = json_decode($this->fields['extra_options'], true);
  394. } catch (Exception $ex) {
  395. $extra = array();
  396. }
  397. if (!empty($extra)) {
  398. $default = array_merge($default, $extra);
  399. }
  400. }
  401. $options = array_merge($default, $options);
  402. $this->_provider = self::createInstance($type, $options, $collaborators);
  403. }
  404. return $this->_provider;
  405. }
  406. /**
  407. *
  408. * @return boolean|string
  409. */
  410. public function checkAuthorization() {
  411. if ($this->_provider === null) {
  412. return false;
  413. }
  414. if (!isset($_GET['code'])) {
  415. $scope = array();
  416. if (!empty($this->fields['scope'])) {
  417. $scope = explode(',', $this->fields['scope']);
  418. }
  419. $options = array(
  420. 'scope' => $scope,
  421. 'state' => Session::getNewCSRFToken(),
  422. );
  423. $this->_provider->authorize($options);
  424. }
  425. // Check given state against previously stored one to mitigate CSRF attack
  426. $state = isset($_GET['state']) ? $_GET['state'] : '';
  427. Session::checkCSRF(array(
  428. '_glpi_csrf_token' => $state,
  429. ));
  430. $this->_code = $_GET['code'];
  431. return $_GET['code'];
  432. }
  433. /**
  434. *
  435. * @return boolean|\League\OAuth2\Client\Token\AccessToken
  436. */
  437. public function getAccessToken() {
  438. if ($this->_token !== null) {
  439. return $this->_token;
  440. }
  441. if ($this->_provider === null || $this->_code === null) {
  442. return false;
  443. }
  444. $this->_token = $this->_provider->getAccessToken('authorization_code', array(
  445. 'code' => $this->_code
  446. ));
  447. return $this->_token;
  448. }
  449. /**
  450. *
  451. * @return boolean|\League\OAuth2\Client\Provider\ResourceOwnerInterface
  452. */
  453. public function getResourceOwner() {
  454. if ($this->_resource_owner !== null) {
  455. return $this->_resource_owner;
  456. }
  457. $token = $this->getAccessToken();
  458. if (!$token) {
  459. return false;
  460. }
  461. $this->_resource_owner = $this->_provider->getResourceOwner($token);
  462. return $this->_resource_owner;
  463. }
  464. public function findUser() {
  465. $resource = $this->getResourceOwner();
  466. $resource_array = $resource->toArray();
  467. $user = new User();
  468. //First: check linked user
  469. $email = false;
  470. $email_fields = array('email', 'e-mail', 'email-address');
  471. foreach ($email_fields as $field) {
  472. if (isset($resource_array[$field]) && is_string($resource_array[$field])) {
  473. $email = $resource_array[$field];
  474. break;
  475. }
  476. }
  477. $default_condition = '';
  478. if (version_compare(GLPI_VERSION, '9.3', '>=')) {
  479. $default_condition = array();
  480. }
  481. if ($email && $user->getFromDBbyEmail($email, $default_condition)) {
  482. return $user;
  483. }
  484. $login = false;
  485. $login_fields = array('login', 'username');
  486. foreach ($login_fields as $field) {
  487. if (isset($resource_array[$field]) && is_string($resource_array[$field])) {
  488. $login = $resource_array[$field];
  489. break;
  490. }
  491. }
  492. if ($login && $user->getFromDBbyName($login)) {
  493. return $user;
  494. }
  495. return false;
  496. }
  497. public function login() {
  498. $user = $this->findUser();
  499. if (!$user) {
  500. return false;
  501. }
  502. //Create fake auth
  503. $auth = new Auth();
  504. $auth->user = $user;
  505. $auth->auth_succeded = true;
  506. $auth->extauth = 1;
  507. $auth->user_present = $auth->user->getFromDBbyName(addslashes($user->fields['name']));
  508. $auth->user->fields['authtype'] = Auth::DB_GLPI;
  509. Session::init($auth);
  510. return $auth->auth_succeded;
  511. }
  512. }