api_access.class.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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 array $requires role required by API method user / external / admin
  45. */
  46. public static $requires = array('user', 'external', 'admin');
  47. /**
  48. * @var string $role user role
  49. */
  50. public static $role = 'user';
  51. /**
  52. * @var User $user Loggued user
  53. */
  54. public static $user = '';
  55. /**
  56. * Constructor
  57. */
  58. public function __construct()
  59. {
  60. global $db;
  61. $this->db = $db;
  62. }
  63. // phpcs:disable PEAR.NamingConventions.ValidFunctionName
  64. /**
  65. * Check access
  66. *
  67. * @return bool
  68. *
  69. * @throws RestException 401 Forbidden
  70. * @throws RestException 503 Technical error
  71. */
  72. public function __isAllowed()
  73. {
  74. // phpcs:enable
  75. global $conf, $db, $user;
  76. $login = '';
  77. $stored_key = '';
  78. $userClass = Defaults::$userIdentifierClass;
  79. /*foreach ($_SERVER as $key => $val)
  80. {
  81. dol_syslog($key.' - '.$val);
  82. }*/
  83. // api key can be provided in url with parameter api_key=xxx or ni header with header DOLAPIKEY:xxx
  84. $api_key = '';
  85. if (isset($_GET['api_key'])) { // For backward compatibility
  86. // TODO Add option to disable use of api key on url. Return errors if used.
  87. $api_key = $_GET['api_key'];
  88. }
  89. if (isset($_GET['DOLAPIKEY'])) {
  90. // TODO Add option to disable use of api key on url. Return errors if used.
  91. $api_key = $_GET['DOLAPIKEY']; // With GET method
  92. }
  93. if (isset($_SERVER['HTTP_DOLAPIKEY'])) { // Param DOLAPIKEY in header can be read with HTTP_DOLAPIKEY
  94. $api_key = $_SERVER['HTTP_DOLAPIKEY']; // With header method (recommanded)
  95. }
  96. if ($api_key) {
  97. $userentity = 0;
  98. $sql = "SELECT u.login, u.datec, u.api_key, ";
  99. $sql .= " u.tms as date_modification, u.entity";
  100. $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
  101. $sql .= " WHERE u.api_key = '".$this->db->escape($api_key)."' OR u.api_key = '".$this->db->escape(dolEncrypt($api_key, '', '', 'dolibarr'))."'";
  102. $result = $this->db->query($sql);
  103. if ($result) {
  104. $nbrows = $this->db->num_rows($result);
  105. if ($nbrows == 1) {
  106. $obj = $this->db->fetch_object($result);
  107. $login = $obj->login;
  108. $stored_key = dolDecrypt($obj->api_key);
  109. $userentity = $obj->entity;
  110. 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
  111. $conf->entity = ($obj->entity ? $obj->entity : 1);
  112. // We must also reload global conf to get params from the entity
  113. 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);
  114. $conf->setValues($this->db);
  115. }
  116. } elseif ($nbrows > 1) {
  117. throw new RestException(503, 'Error when fetching user api_key : More than 1 user with this apikey');
  118. }
  119. } else {
  120. throw new RestException(503, 'Error when fetching user api_key :'.$this->db->error_msg);
  121. }
  122. if ($stored_key != $api_key) { // This should not happen since we did a search on api_key
  123. $userClass::setCacheIdentifier($api_key);
  124. return false;
  125. }
  126. if (!$login) {
  127. throw new RestException(503, 'Error when searching login user from api key');
  128. }
  129. $fuser = new User($this->db);
  130. $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)
  131. if ($result <= 0) {
  132. throw new RestException(503, 'Error when fetching user :'.$fuser->error.' (conf->entity='.$conf->entity.')');
  133. }
  134. if ($fuser->statut == 0) {
  135. throw new RestException(503, 'Error when fetching user. This user has been locked or disabled');
  136. }
  137. $fuser->getrights();
  138. // Set the property $user to the $user of API
  139. static::$user = $fuser;
  140. // Set also the global variable $user to the $user of API
  141. $user = $fuser;
  142. if ($fuser->socid) {
  143. static::$role = 'external';
  144. }
  145. if ($fuser->admin) {
  146. static::$role = 'admin';
  147. }
  148. } else {
  149. throw new RestException(401, "Failed to login to API. No parameter 'HTTP_DOLAPIKEY' on HTTP header (and no parameter DOLAPIKEY in URL).");
  150. }
  151. $userClass::setCacheIdentifier(static::$role);
  152. Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess';
  153. $requirefortest = static::$requires;
  154. if (!is_array($requirefortest)) {
  155. $requirefortest = explode(',', $requirefortest);
  156. }
  157. return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin';
  158. }
  159. // phpcs:disable PEAR.NamingConventions.ValidFunctionName
  160. /**
  161. * @return string string to be used with WWW-Authenticate header
  162. */
  163. public function __getWWWAuthenticateString()
  164. {
  165. // phpcs:enable
  166. return '';
  167. }
  168. /**
  169. * Verify access
  170. *
  171. * @param array $m Properties of method
  172. *
  173. * @access private
  174. * @return bool
  175. */
  176. public static function verifyAccess(array $m)
  177. {
  178. $requires = isset($m['class']['DolibarrApiAccess']['properties']['requires'])
  179. ? $m['class']['DolibarrApiAccess']['properties']['requires']
  180. : false;
  181. return $requires
  182. ? static::$role == 'admin' || in_array(static::$role, (array) $requires)
  183. : true;
  184. }
  185. }