provider.class.php 17 KB

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