provider.class.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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 $collaborators = []) {
  300. switch ($type) {
  301. case 'facebook':
  302. if (!isset($options['graphApiVersion'])) {
  303. $options['graphApiVersion'] = 'v2.8';
  304. }
  305. return new League\OAuth2\Client\Provider\Facebook($options, $collaborators);
  306. case 'github':
  307. return new League\OAuth2\Client\Provider\Github($options, $collaborators);
  308. case 'google':
  309. return new League\OAuth2\Client\Provider\Google($options, $collaborators);
  310. case 'instagram':
  311. return new League\OAuth2\Client\Provider\Instagram($options, $collaborators);
  312. case 'linkedin':
  313. return new League\OAuth2\Client\Provider\LinkedIn($options, $collaborators);
  314. case 'generic':
  315. default:
  316. return new League\OAuth2\Client\Provider\GenericProvider($options, $collaborators);
  317. }
  318. }
  319. private function getCurrentURL() {
  320. $currentURL = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? "https://" : "http://";
  321. $currentURL .= $_SERVER["SERVER_NAME"];
  322. if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
  323. $currentURL .= ":" . $_SERVER["SERVER_PORT"];
  324. }
  325. $currentURL .= $_SERVER["REQUEST_URI"];
  326. return $currentURL;
  327. }
  328. public function prepareProviderInstance(array $options = [], array $collaborators = []) {
  329. global $CFG_GLPI;
  330. if ($this->_provider === null) {
  331. $redirect_uri = $this->getCurrentURL();
  332. $type = $this->fields['type'];
  333. $default = [
  334. 'clientId' => $this->fields['client_id'],
  335. 'clientSecret' => $this->fields['client_secret'],
  336. 'redirectUri' => $redirect_uri,
  337. ];
  338. if ($type === 'generic') {
  339. $default['urlAuthorize'] = $this->fields['url_authorize'];
  340. $default['urlAccessToken'] = $this->fields['url_accessToken'];
  341. $default['urlResourceOwnerDetails'] = $this->fields['url_resource_owner_details'];
  342. }
  343. if (!empty($this->fields['extra_options'])) {
  344. try {
  345. $extra = json_decode($this->fields['extra_options'], true);
  346. if (!empty($extra)) {
  347. $default = array_merge($default, $extra);
  348. }
  349. } catch (Exception $ex) {
  350. }
  351. }
  352. $options = array_merge($default, $options);
  353. $this->_provider = self::createInstance($type, $options, $collaborators);
  354. }
  355. return $this->_provider;
  356. }
  357. /**
  358. *
  359. * @return boolean|string
  360. */
  361. public function checkAuthorization() {
  362. if ($this->_provider === null) {
  363. return false;
  364. }
  365. if (!isset($_GET['code'])) {
  366. $scope = [];
  367. if (!empty($this->fields['scope'])) {
  368. $scope = explode(',', $this->fields['scope']);
  369. }
  370. $options = [
  371. 'scope' => $scope,
  372. 'state' => Session::getNewCSRFToken(),
  373. ];
  374. $this->_provider->authorize($options);
  375. }
  376. // Check given state against previously stored one to mitigate CSRF attack
  377. $state = isset($_GET['state']) ? $_GET['state'] : '';
  378. Session::checkCSRF([
  379. '_glpi_csrf_token' => $state,
  380. ]);
  381. $this->_code = $_GET['code'];
  382. return $_GET['code'];
  383. }
  384. /**
  385. *
  386. * @return boolean|\League\OAuth2\Client\Token\AccessToken
  387. */
  388. public function getAccessToken() {
  389. if ($this->_token !== null) {
  390. return $this->_token;
  391. }
  392. if ($this->_provider === null || $this->_code === null) {
  393. return false;
  394. }
  395. $this->_token = $this->_provider->getAccessToken('authorization_code', [
  396. 'code' => $this->_code
  397. ]);
  398. return $this->_token;
  399. }
  400. /**
  401. *
  402. * @return boolean|\League\OAuth2\Client\Provider\ResourceOwnerInterface
  403. */
  404. public function getResourceOwner() {
  405. if ($this->_resource_owner !== null) {
  406. return $this->_resource_owner;
  407. }
  408. $token = $this->getAccessToken();
  409. if (!$token) {
  410. return false;
  411. }
  412. $this->_resource_owner = $this->_provider->getResourceOwner($token);
  413. return $this->_resource_owner;
  414. }
  415. public function findUser() {
  416. $resource = $this->getResourceOwner();
  417. $resource_array = $resource->toArray();
  418. $user = new User();
  419. //First: check linked user
  420. $email = false;
  421. $email_fields = ['email', 'e-mail'];
  422. foreach ($email_fields as $field) {
  423. if (isset($resource_array[$field]) && is_string($resource_array[$field])) {
  424. $email = $resource_array[$field];
  425. break;
  426. }
  427. }
  428. if ($email && $user->getFromDBbyEmail($email, '')) {
  429. return $user;
  430. }
  431. $login = false;
  432. $login_fields = ['login', 'username'];
  433. foreach ($login_fields as $field) {
  434. if (isset($resource_array[$field]) && is_string($resource_array[$field])) {
  435. $login = $resource_array[$field];
  436. break;
  437. }
  438. }
  439. if ($login && $user->getFromDBbyName($login)) {
  440. return $user;
  441. }
  442. return false;
  443. }
  444. public function login() {
  445. $user = $this->findUser();
  446. if (!$user) {
  447. return false;
  448. }
  449. //Create fake auth
  450. $auth = new Auth();
  451. $auth->user = $user;
  452. $auth->auth_succeded = true;
  453. $auth->extauth = 1;
  454. $auth->user_present = $auth->user->getFromDBbyName(addslashes($user->fields['name']));
  455. $auth->user->fields['authtype'] = Auth::DB_GLPI;
  456. Session::init($auth);
  457. return $auth->auth_succeded;
  458. }
  459. }