dolibarr  19.0.0-dev
api_access.class.php
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 
20 // Create the autoloader for Luracast
21 require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/AutoLoader.php';
22 call_user_func(function () {
23  $loader = Luracast\Restler\AutoLoader::instance();
24  spl_autoload_register($loader);
25  return $loader;
26 });
27 
28 require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/iAuthenticate.php';
29 require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/iUseAuthentication.php';
30 require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Resources.php';
31 require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Defaults.php';
32 require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/RestException.php';
33 use Luracast\Restler\iAuthenticate;
34 use Luracast\Restler\iUseAuthentication;
35 use Luracast\Restler\Resources;
36 use Luracast\Restler\Defaults;
37 use Luracast\Restler\RestException;
38 
43 class DolibarrApiAccess implements iAuthenticate
44 {
45  const REALM = 'Restricted Dolibarr API';
46 
50  public static $requires = array('user', 'external', 'admin');
51 
55  public static $role = 'user';
56 
60  public static $user = '';
61 
62 
66  public function __construct()
67  {
68  global $db;
69  $this->db = $db;
70  }
71 
72  // phpcs:disable PEAR.NamingConventions.ValidFunctionName
81  public function __isAllowed()
82  {
83  // phpcs:enable
84  global $conf, $db, $user;
85 
86  $login = '';
87  $stored_key = '';
88 
89  $userClass = Defaults::$userIdentifierClass;
90 
91  /*foreach ($_SERVER as $key => $val)
92  {
93  dol_syslog($key.' - '.$val);
94  }*/
95 
96  // api key can be provided in url with parameter api_key=xxx or ni header with header DOLAPIKEY:xxx
97  $api_key = '';
98  if (isset($_GET['api_key'])) { // For backward compatibility
99  // TODO Add option to disable use of api key on url. Return errors if used.
100  $api_key = $_GET['api_key'];
101  }
102  if (isset($_GET['DOLAPIKEY'])) {
103  // TODO Add option to disable use of api key on url. Return errors if used.
104  $api_key = $_GET['DOLAPIKEY']; // With GET method
105  }
106  if (isset($_SERVER['HTTP_DOLAPIKEY'])) { // Param DOLAPIKEY in header can be read with HTTP_DOLAPIKEY
107  $api_key = $_SERVER['HTTP_DOLAPIKEY']; // With header method (recommanded)
108  }
109  if (preg_match('/^dolcrypt:/i', $api_key)) {
110  throw new RestException(503, 'Bad value for the API key. An API key should not start with dolcrypt:');
111  }
112 
113  if ($api_key) {
114  $userentity = 0;
115 
116  $sql = "SELECT u.login, u.datec, u.api_key,";
117  $sql .= " u.tms as date_modification, u.entity";
118  $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
119  $sql .= " WHERE u.api_key = '".$this->db->escape($api_key)."' OR u.api_key = '".$this->db->escape(dolEncrypt($api_key, '', '', 'dolibarr'))."'";
120 
121  $result = $this->db->query($sql);
122  if ($result) {
123  $nbrows = $this->db->num_rows($result);
124  if ($nbrows == 1) {
125  $obj = $this->db->fetch_object($result);
126  $login = $obj->login;
127  $stored_key = dolDecrypt($obj->api_key);
128  $userentity = $obj->entity;
129 
130  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
131  $conf->entity = ($obj->entity ? $obj->entity : 1);
132  // We must also reload global conf to get params from the entity
133  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);
134  $conf->setValues($this->db);
135  }
136  } elseif ($nbrows > 1) {
137  throw new RestException(503, 'Error when fetching user api_key : More than 1 user with this apikey');
138  }
139  } else {
140  throw new RestException(503, 'Error when fetching user api_key :'.$this->db->error_msg);
141  }
142 
143  if ($login && $stored_key != $api_key) { // This should not happen since we did a search on api_key
144  $userClass::setCacheIdentifier($api_key);
145  return false;
146  }
147 
148  $genericmessageerroruser = 'Error user not valid (not found with api key or bad status or bad validity dates) (conf->entity='.$conf->entity.')';
149 
150  if (!$login) {
151  dol_syslog("functions_isallowed::check_user_api_key Authentication KO for api key: Error when searching login user from api key", LOG_NOTICE);
152  sleep(1); // Anti brut force protection. Must be same delay when user and password are not valid.
153  throw new RestException(401, $genericmessageerroruser);
154  }
155 
156  $fuser = new User($this->db);
157  $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)
158  if ($result <= 0) {
159  dol_syslog("functions_isallowed::check_user_api_key Authentication KO for '".$login."': Failed to fetch on entity", LOG_NOTICE);
160  sleep(1); // Anti brut force protection. Must be same delay when user and password are not valid.
161  throw new RestException(401, $genericmessageerroruser);
162  }
163 
164  // Check if user status is enabled
165  if ($fuser->statut != $fuser::STATUS_ENABLED) {
166  // Status is disabled
167  dol_syslog("functions_isallowed::check_user_api_key Authentication KO for '".$login."': The user has been disabled", LOG_NOTICE);
168  sleep(1); // Anti brut force protection. Must be same delay when user and password are not valid.
169  throw new RestException(401, $genericmessageerroruser);
170  }
171 
172  // Check if session was unvalidated by a password change
173  if (($fuser->flagdelsessionsbefore && !empty($_SESSION["dol_logindate"]) && $fuser->flagdelsessionsbefore > $_SESSION["dol_logindate"])) {
174  // Session is no more valid
175  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.");
176  sleep(1); // Anti brut force protection. Must be same delay when user and password are not valid.
177  throw new RestException(401, $genericmessageerroruser);
178  }
179 
180  // Check date validity
181  if ($fuser->isNotIntoValidityDateRange()) {
182  // User validity dates are no more valid
183  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());
184  sleep(1); // Anti brut force protection. Must be same delay when user and password are not valid.
185  throw new RestException(401, $genericmessageerroruser);
186  }
187 
188  // User seems valid
189  $fuser->getrights();
190 
191  // Set the property $user to the $user of API
192  static::$user = $fuser;
193 
194  // Set also the global variable $user to the $user of API
195  $user = $fuser;
196 
197  if ($fuser->socid) {
198  static::$role = 'external';
199  }
200 
201  if ($fuser->admin) {
202  static::$role = 'admin';
203  }
204  } else {
205  throw new RestException(401, "Failed to login to API. No parameter 'HTTP_DOLAPIKEY' on HTTP header (and no parameter DOLAPIKEY in URL).");
206  }
207 
208  $userClass::setCacheIdentifier(static::$role);
209  Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess';
210  $requirefortest = static::$requires;
211  if (!is_array($requirefortest)) {
212  $requirefortest = explode(',', $requirefortest);
213  }
214  return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin';
215  }
216 
217  // phpcs:disable PEAR.NamingConventions.ValidFunctionName
221  public function __getWWWAuthenticateString()
222  {
223  // phpcs:enable
224  return '';
225  }
226 
235  public static function verifyAccess(array $m)
236  {
237  $requires = isset($m['class']['DolibarrApiAccess']['properties']['requires'])
238  ? $m['class']['DolibarrApiAccess']['properties']['requires']
239  : false;
240 
241 
242  return $requires
243  ? static::$role == 'admin' || in_array(static::$role, (array) $requires)
244  : true;
245  }
246 }
Dolibarr API access class.
__construct()
Constructor.
__isAllowed()
Check access.
static verifyAccess(array $m)
Verify access.
Class to manage Dolibarr users.
Definition: user.class.php:48
if(isModEnabled('facture') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:746
dol_now($mode='auto')
Return date for now.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dolEncrypt($chain, $key='', $ciphering='AES-256-CTR', $forceseed='')
Encode a string with a symetric encryption.
dolDecrypt($chain, $key='')
Decode a string with a symetric encryption.