provider.class.php 19 KB

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