api_access.class.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. <?php
  2. /* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  3. * Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. // Create the autoloader for Luracast
  19. require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/AutoLoader.php';
  20. call_user_func(function () {
  21. $loader = Luracast\Restler\AutoLoader::instance();
  22. spl_autoload_register($loader);
  23. return $loader;
  24. });
  25. require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/iAuthenticate.php';
  26. require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/iUseAuthentication.php';
  27. require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Resources.php';
  28. require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Defaults.php';
  29. require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/RestException.php';
  30. use \Luracast\Restler\iAuthenticate;
  31. use \Luracast\Restler\iUseAuthentication;
  32. use \Luracast\Restler\Resources;
  33. use \Luracast\Restler\Defaults;
  34. use \Luracast\Restler\RestException;
  35. /**
  36. * Dolibarr API access class
  37. *
  38. */
  39. class DolibarrApiAccess implements iAuthenticate
  40. {
  41. const REALM = 'Restricted Dolibarr API';
  42. /**
  43. * @var array $requires role required by API method user / external / admin
  44. */
  45. public static $requires = array('user', 'external', 'admin');
  46. /**
  47. * @var string $role user role
  48. */
  49. public static $role = 'user';
  50. /**
  51. * @var User $user Loggued user
  52. */
  53. public static $user = '';
  54. // phpcs:disable PEAR.NamingConventions.ValidFunctionName
  55. /**
  56. * Check access
  57. *
  58. * @return bool
  59. *
  60. * @throws RestException 401 Forbidden
  61. * @throws RestException 503 Technical error
  62. */
  63. public function __isAllowed()
  64. {
  65. // phpcs:enable
  66. global $conf, $db;
  67. $login = '';
  68. $stored_key = '';
  69. $userClass = Defaults::$userIdentifierClass;
  70. /*foreach ($_SERVER as $key => $val)
  71. {
  72. dol_syslog($key.' - '.$val);
  73. }*/
  74. // api key can be provided in url with parameter api_key=xxx or ni header with header DOLAPIKEY:xxx
  75. $api_key = '';
  76. if (isset($_GET['api_key'])) // For backward compatibility
  77. {
  78. // TODO Add option to disable use of api key on url. Return errors if used.
  79. $api_key = $_GET['api_key'];
  80. }
  81. if (isset($_GET['DOLAPIKEY']))
  82. {
  83. // TODO Add option to disable use of api key on url. Return errors if used.
  84. $api_key = $_GET['DOLAPIKEY']; // With GET method
  85. }
  86. if (isset($_SERVER['HTTP_DOLAPIKEY'])) // Param DOLAPIKEY in header can be read with HTTP_DOLAPIKEY
  87. {
  88. $api_key = $_SERVER['HTTP_DOLAPIKEY']; // With header method (recommanded)
  89. }
  90. if ($api_key)
  91. {
  92. $userentity = 0;
  93. $sql = "SELECT u.login, u.datec, u.api_key, ";
  94. $sql .= " u.tms as date_modification, u.entity";
  95. $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
  96. $sql .= " WHERE u.api_key = '".$db->escape($api_key)."'";
  97. // TODO Check if 2 users has same API key.
  98. $result = $db->query($sql);
  99. if ($result)
  100. {
  101. if ($db->num_rows($result))
  102. {
  103. $obj = $db->fetch_object($result);
  104. $login = $obj->login;
  105. $stored_key = $obj->api_key;
  106. $userentity = $obj->entity;
  107. if (!defined("DOLENTITY") && $conf->entity != ($obj->entity ? $obj->entity : 1)) // If API was not forced with HTTP_DOLENTITY, and user is on another entity, so we reset entity to entity of user
  108. {
  109. $conf->entity = ($obj->entity ? $obj->entity : 1);
  110. // We must also reload global conf to get params from the entity
  111. dol_syslog("Entity was not set on http header with HTTP_DOLAPIENTITY (recommanded for performance purpose), so we switch now on entity of user (".$conf->entity.") and we have to reload configuration.", LOG_WARNING);
  112. $conf->setValues($db);
  113. }
  114. }
  115. } else {
  116. throw new RestException(503, 'Error when fetching user api_key :'.$db->error_msg);
  117. }
  118. if ($stored_key != $api_key) { // This should not happen since we did a search on api_key
  119. $userClass::setCacheIdentifier($api_key);
  120. return false;
  121. }
  122. if (!$login)
  123. {
  124. throw new RestException(503, 'Error when searching login user from api key');
  125. }
  126. $fuser = new User($db);
  127. $result = $fuser->fetch('', $login, '', 0, (empty($userentity) ? -1 : $conf->entity)); // If user is not entity 0, we search in working entity $conf->entity (that may have been forced to a different value than user entity)
  128. if ($result <= 0) {
  129. throw new RestException(503, 'Error when fetching user :'.$fuser->error.' (conf->entity='.$conf->entity.')');
  130. }
  131. $fuser->getrights();
  132. static::$user = $fuser;
  133. if ($fuser->socid) {
  134. static::$role = 'external';
  135. }
  136. if ($fuser->admin) {
  137. static::$role = 'admin';
  138. }
  139. } else {
  140. throw new RestException(401, "Failed to login to API. No parameter 'HTTP_DOLAPIKEY' on HTTP header (and no parameter DOLAPIKEY in URL).");
  141. }
  142. $userClass::setCacheIdentifier(static::$role);
  143. Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess';
  144. $requirefortest = static::$requires;
  145. if (!is_array($requirefortest)) $requirefortest = explode(',', $requirefortest);
  146. return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin';
  147. }
  148. // phpcs:disable PEAR.NamingConventions.ValidFunctionName
  149. /**
  150. * @return string string to be used with WWW-Authenticate header
  151. */
  152. public function __getWWWAuthenticateString()
  153. {
  154. // phpcs:enable
  155. return '';
  156. }
  157. /**
  158. * Verify access
  159. *
  160. * @param array $m Properties of method
  161. *
  162. * @access private
  163. * @return bool
  164. */
  165. public static function verifyAccess(array $m)
  166. {
  167. $requires = isset($m['class']['DolibarrApiAccess']['properties']['requires'])
  168. ? $m['class']['DolibarrApiAccess']['properties']['requires']
  169. : false;
  170. return $requires
  171. ? static::$role == 'admin' || in_array(static::$role, (array) $requires)
  172. : true;
  173. }
  174. }