api_access.class.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. <?php
  2. /* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  3. * Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2023 Ferran Marcet <fmarcet@2byte.es>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. // Create the autoloader for Luracast
  20. require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/AutoLoader.php';
  21. call_user_func(function () {
  22. $loader = Luracast\Restler\AutoLoader::instance();
  23. spl_autoload_register($loader);
  24. return $loader;
  25. });
  26. require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/iAuthenticate.php';
  27. require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/iUseAuthentication.php';
  28. require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Resources.php';
  29. require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Defaults.php';
  30. require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/RestException.php';
  31. use Luracast\Restler\iAuthenticate;
  32. use Luracast\Restler\iUseAuthentication;
  33. use Luracast\Restler\Resources;
  34. use Luracast\Restler\Defaults;
  35. use Luracast\Restler\RestException;
  36. /**
  37. * Dolibarr API access class
  38. *
  39. */
  40. class DolibarrApiAccess implements iAuthenticate
  41. {
  42. const REALM = 'Restricted Dolibarr API';
  43. /**
  44. * @var DoliDB Database handler
  45. */
  46. public $db;
  47. /**
  48. * @var array $requires role required by API method user / external / admin
  49. */
  50. public static $requires = array('user', 'external', 'admin');
  51. /**
  52. * @var string $role user role
  53. */
  54. public static $role = 'user';
  55. /**
  56. * @var User $user Loggued user
  57. */
  58. public static $user = '';
  59. /**
  60. * Constructor
  61. */
  62. public function __construct()
  63. {
  64. global $db;
  65. $this->db = $db;
  66. }
  67. // phpcs:disable PEAR.NamingConventions.ValidFunctionName
  68. /**
  69. * Check access
  70. *
  71. * @return bool
  72. *
  73. * @throws RestException 401 Forbidden
  74. * @throws RestException 503 Technical error
  75. */
  76. public function __isAllowed()
  77. {
  78. // phpcs:enable
  79. global $conf, $db, $user;
  80. $login = '';
  81. $stored_key = '';
  82. $userClass = Defaults::$userIdentifierClass;
  83. /*foreach ($_SERVER as $key => $val)
  84. {
  85. dol_syslog($key.' - '.$val);
  86. }*/
  87. // api key can be provided in url with parameter api_key=xxx or ni header with header DOLAPIKEY:xxx
  88. $api_key = '';
  89. if (isset($_GET['api_key'])) { // For backward compatibility
  90. // TODO Add option to disable use of api key on url. Return errors if used.
  91. $api_key = $_GET['api_key'];
  92. }
  93. if (isset($_GET['DOLAPIKEY'])) {
  94. // TODO Add option to disable use of api key on url. Return errors if used.
  95. $api_key = $_GET['DOLAPIKEY']; // With GET method
  96. }
  97. if (isset($_SERVER['HTTP_DOLAPIKEY'])) { // Param DOLAPIKEY in header can be read with HTTP_DOLAPIKEY
  98. $api_key = $_SERVER['HTTP_DOLAPIKEY']; // With header method (recommanded)
  99. }
  100. if (preg_match('/^dolcrypt:/i', $api_key)) {
  101. throw new RestException(503, 'Bad value for the API key. An API key should not start with dolcrypt:');
  102. }
  103. if ($api_key) {
  104. $userentity = 0;
  105. $sql = "SELECT u.login, u.datec, u.api_key,";
  106. $sql .= " u.tms as date_modification, u.entity";
  107. $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
  108. $sql .= " WHERE u.api_key = '".$this->db->escape($api_key)."' OR u.api_key = '".$this->db->escape(dolEncrypt($api_key, '', '', 'dolibarr'))."'";
  109. $result = $this->db->query($sql);
  110. if ($result) {
  111. $nbrows = $this->db->num_rows($result);
  112. if ($nbrows == 1) {
  113. $obj = $this->db->fetch_object($result);
  114. $login = $obj->login;
  115. $stored_key = dolDecrypt($obj->api_key);
  116. $userentity = $obj->entity;
  117. 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
  118. $conf->entity = ($obj->entity ? $obj->entity : 1);
  119. // We must also reload global conf to get params from the entity
  120. 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);
  121. $conf->setValues($this->db);
  122. }
  123. } elseif ($nbrows > 1) {
  124. throw new RestException(503, 'Error when fetching user api_key : More than 1 user with this apikey');
  125. }
  126. } else {
  127. throw new RestException(503, 'Error when fetching user api_key :'.$this->db->error_msg);
  128. }
  129. if ($login && $stored_key != $api_key) { // This should not happen since we did a search on api_key
  130. $userClass::setCacheIdentifier($api_key);
  131. return false;
  132. }
  133. $genericmessageerroruser = 'Error user not valid (not found with api key or bad status or bad validity dates) (conf->entity='.$conf->entity.')';
  134. if (!$login) {
  135. dol_syslog("functions_isallowed::check_user_api_key Authentication KO for api key: Error when searching login user from api key", LOG_NOTICE);
  136. sleep(1); // Anti brut force protection. Must be same delay when user and password are not valid.
  137. throw new RestException(401, $genericmessageerroruser);
  138. }
  139. $fuser = new User($this->db);
  140. $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)
  141. if ($result <= 0) {
  142. dol_syslog("functions_isallowed::check_user_api_key Authentication KO for '".$login."': Failed to fetch on entity", LOG_NOTICE);
  143. sleep(1); // Anti brut force protection. Must be same delay when user and password are not valid.
  144. throw new RestException(401, $genericmessageerroruser);
  145. }
  146. // Check if user status is enabled
  147. if ($fuser->statut != $fuser::STATUS_ENABLED) {
  148. // Status is disabled
  149. dol_syslog("functions_isallowed::check_user_api_key Authentication KO for '".$login."': The user has been disabled", LOG_NOTICE);
  150. sleep(1); // Anti brut force protection. Must be same delay when user and password are not valid.
  151. throw new RestException(401, $genericmessageerroruser);
  152. }
  153. // Check if session was unvalidated by a password change
  154. if (($fuser->flagdelsessionsbefore && !empty($_SESSION["dol_logindate"]) && $fuser->flagdelsessionsbefore > $_SESSION["dol_logindate"])) {
  155. // Session is no more valid
  156. dol_syslog("functions_isallowed::check_user_api_key Authentication KO for '".$login."': The user has a date for session invalidation = ".$fuser->flagdelsessionsbefore." and a session date = ".$_SESSION["dol_logindate"].". We must invalidate its sessions.");
  157. sleep(1); // Anti brut force protection. Must be same delay when user and password are not valid.
  158. throw new RestException(401, $genericmessageerroruser);
  159. }
  160. // Check date validity
  161. if ($fuser->isNotIntoValidityDateRange()) {
  162. // User validity dates are no more valid
  163. dol_syslog("functions_isallowed::check_user_api_key Authentication KO for '".$login."': The user login has a validity between [".$fuser->datestartvalidity." and ".$fuser->dateendvalidity."], curren date is ".dol_now());
  164. sleep(1); // Anti brut force protection. Must be same delay when user and password are not valid.
  165. throw new RestException(401, $genericmessageerroruser);
  166. }
  167. // User seems valid
  168. $fuser->getrights();
  169. // Set the property $user to the $user of API
  170. static::$user = $fuser;
  171. // Set also the global variable $user to the $user of API
  172. $user = $fuser;
  173. if ($fuser->socid) {
  174. static::$role = 'external';
  175. }
  176. if ($fuser->admin) {
  177. static::$role = 'admin';
  178. }
  179. } else {
  180. throw new RestException(401, "Failed to login to API. No parameter 'HTTP_DOLAPIKEY' on HTTP header (and no parameter DOLAPIKEY in URL).");
  181. }
  182. $userClass::setCacheIdentifier(static::$role);
  183. Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess';
  184. $requirefortest = static::$requires;
  185. if (!is_array($requirefortest)) {
  186. $requirefortest = explode(',', $requirefortest);
  187. }
  188. return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin';
  189. }
  190. // phpcs:disable PEAR.NamingConventions.ValidFunctionName
  191. /**
  192. * @return string string to be used with WWW-Authenticate header
  193. */
  194. public function __getWWWAuthenticateString()
  195. {
  196. // phpcs:enable
  197. return '';
  198. }
  199. /**
  200. * Verify access
  201. *
  202. * @param array $m Properties of method
  203. *
  204. * @access private
  205. * @return bool
  206. */
  207. public static function verifyAccess(array $m)
  208. {
  209. $requires = isset($m['class']['DolibarrApiAccess']['properties']['requires'])
  210. ? $m['class']['DolibarrApiAccess']['properties']['requires']
  211. : false;
  212. return $requires
  213. ? static::$role == 'admin' || in_array(static::$role, (array) $requires)
  214. : true;
  215. }
  216. }