dolibarr 23.0.3
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 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21// Create the autoloader for Luracast
22require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/AutoLoader.php';
23call_user_func(
27 static function () {
28 $loader = Luracast\Restler\AutoLoader::instance();
29 spl_autoload_register($loader);
30 return $loader;
31 }
32);
33
34require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/iAuthenticate.php';
35require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/iUseAuthentication.php';
36require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Resources.php';
37require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Defaults.php';
38require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/RestException.php';
39
40use Luracast\Restler\iAuthenticate;
41use Luracast\Restler\Resources;
42use Luracast\Restler\Defaults;
43use Luracast\Restler\RestException;
44
48class DolibarrApiAccess implements iAuthenticate
49{
50 const REALM = 'Restricted Dolibarr API';
51
55 public $db;
56
60 public static $requires = array('user', 'external', 'admin');
61
65 public static $role = 'user';
66
70 public static $user = null;
71
72
76 public function __construct()
77 {
78 global $db;
79 $this->db = $db;
80 }
81
82 // phpcs:disable PEAR.NamingConventions.ValidFunctionName
91 public function __isAllowed()
92 {
93 // phpcs:enable
94 global $conf, $langs, $user;
95
96 $login = '';
97 $stored_key = '';
98
99 $userClass = Defaults::$userIdentifierClass;
100
101 /*foreach ($_SERVER as $key => $val)
102 {
103 dol_syslog($key.' - '.$val);
104 }*/
105
106 // api key can be provided in url with parameter api_key=xxx or ni header with header DOLAPIKEY:xxx
107 $api_key = '';
108 if (isset($_GET['api_key'])) { // For backward compatibility. Keep $_GET here.
109 // TODO Add option to disable use of api key on url. Return errors if used.
110 $api_key = $_GET['api_key'];
111 }
112 if (isset($_GET['DOLAPIKEY'])) {
113 // TODO Add option to disable use of api key on url. Return errors if used.
114 $api_key = $_GET['DOLAPIKEY']; // With GET method
115 }
116
117 // TODO Can filter on user agent.
118 //$api_useragent = $_SERVER['HTTP_USER_AGENT'];
119
120 if (isset($_SERVER['HTTP_DOLAPIKEY'])) { // HTTP Header entry "DOLAPIKEY: ..." can be read with $_SERVER["HTTP_DOLAPIKEY"]
121 $api_key = $_SERVER['HTTP_DOLAPIKEY']; // With header method (recommended)
122 } elseif (empty($api_key)) {
123 $headers = getallheaders(); // HTTP Header entry "Authorization: Bearer ..." can be read with getallheaders
124 $api_key = preg_replace('/^Bearer\s+/i', '', empty($headers['Authorization']) ? '' : $headers['Authorization']);
125 };
126
127 $api_key = dol_string_nounprintableascii($api_key, 1);
128
129 if (preg_match('/^dolcrypt:/i', $api_key)) {
130 throw new RestException(503, 'Bad value for the API key. An API key should not start with dolcrypt:');
131 }
132
133 if ($api_key) {
134 $userentity = 0;
135 $token_rowid = 0;
136
137 if (!getDolGlobalString('API_IN_TOKEN_TABLE')) {
138 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE') && defined("DOLENTITY")) {
139 $sql = "SELECT u.login, u.datec, u.api_key as use_api, u.api_key as api_key, 0 as token_rowid,";
140 $sql .= " u.tms as date_modification,";
141 $sql .= " gu.entity, gu.entity as token_entity";
142 $sql .= " FROM ".$this->db->prefix()."user as u";
143 $sql .= " JOIN ".$this->db->prefix()."usergroup_user as gu ON u.rowid = gu.fk_user AND gu.entity = ".((int) $conf->entity);
144 $sql .= " WHERE u.api_key = '".$this->db->escape($api_key)."' OR u.api_key = '".$this->db->escape(dolEncrypt($api_key, '', '', 'dolibarr'))."'";
145 } else {
146 $sql = "SELECT u.login, u.datec, u.api_key as use_api, u.entity, u.api_key as api_key, u.entity as token_entity, 0 as token_rowid,";
147 $sql .= " u.tms as date_modification";
148 $sql .= " FROM ".$this->db->prefix()."user as u";
149 $sql .= " WHERE u.api_key = '".$this->db->escape($api_key)."' OR u.api_key = '".$this->db->escape(dolEncrypt($api_key, '', '', 'dolibarr'))."'";
150 }
151 } else {
152 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE') && defined("DOLENTITY")) {
153 $sql = "SELECT u.login, u.datec, u.api_key as use_api, oat.tokenstring as api_key, oat.entity as token_entity, rowid as token_rowid,";
154 $sql .= " oat.tms as date_modification,";
155 $sql .= " gu.entity";
156 $sql .= " FROM ".$this->db->prefix()."oauth_token AS oat";
157 $sql .= " JOIN ".$this->db->prefix()."user AS u ON u.rowid = oat.fk_user";
158 $sql .= " JOIN ".$this->db->prefix()."usergroup_user as gu ON u.rowid = gu.fk_user AND gu.entity = ".((int) $conf->entity);
159 $sql .= " WHERE (oat.tokenstring = '".$this->db->escape($api_key)."'";
160 $sql .= " OR oat.tokenstring = '".$this->db->escape(dolEncrypt($api_key, '', '', 'dolibarr'))."')";
161 $sql .= " AND gu.entity = oat.entity";
162 $sql .= " AND oat.service = 'dolibarr_rest_api'";
163 } else {
164 $sql = "SELECT u.login, u.datec, u.api_key as use_api, u.entity, oat.tokenstring as api_key, oat.entity as token_entity, rowid as token_rowid,";
165 $sql .= " oat.tms as date_modification";
166 $sql .= " FROM ".$this->db->prefix()."oauth_token AS oat";
167 $sql .= " JOIN ".$this->db->prefix()."user AS u ON u.rowid = oat.fk_user";
168 $sql .= " WHERE (oat.tokenstring = '".$this->db->escape($api_key)."'";
169 $sql .= " OR oat.tokenstring = '".$this->db->escape(dolEncrypt($api_key, '', '', 'dolibarr'))."')";
170 $sql .= " AND oat.service = 'dolibarr_rest_api'";
171 }
172 }
173
174 $result = $this->db->query($sql);
175 if ($result) {
176 $nbrows = $this->db->num_rows($result);
177 if ($nbrows == 1) {
178 $obj = $this->db->fetch_object($result);
179
180 $login = $obj->login;
181 $stored_key = dolDecrypt($obj->api_key);
182 $userentity = $obj->entity;
183 $token_entity = $obj->token_entity;
184 $token_rowid = $obj->token_rowid;
185
186 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
187 $conf->entity = ($obj->entity ? $obj->entity : 1);
188 // We must also reload global conf to get params from the entity
189 dol_syslog("Entity was not set on http header with HTTP_DOLAPIENTITY (recommended for performance purpose), so we switch now on entity of user (".$conf->entity.") and we have to reload configuration.", LOG_WARNING);
190 $conf->setValues($this->db);
191
192 // set global mysoc after setting conf entity (the entity can be changed with the user logged)
193 // see master.inc.php
194 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
195
196 $fmysoc = new Societe($this->db);
197 $fmysoc->setMysoc($conf);
198
199 // We set some specific default values according to country
200 if ($fmysoc->country_code == 'DE' && !isset($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) {
201 // For DE, we need to invert our address with customer address
202 $conf->global->MAIN_INVERT_SENDER_RECIPIENT = 1;
203 }
204 if ($fmysoc->country_code == 'FR' && !isset($conf->global->INVOICE_CATEGORY_OF_OPERATION)) {
205 // For FR, default value of option to show category of operations is on by default. Decret n°2099-1299 2022-10-07
206 $conf->global->INVOICE_CATEGORY_OF_OPERATION = 1;
207 }
208 if ($fmysoc->country_code == 'FR' && !isset($conf->global->INVOICE_DISABLE_REPLACEMENT)) {
209 // For FR, the replacement invoice type is not allowed.
210 // From an accounting point of view, this creates holes in the numbering of the invoice.
211 // This is very problematic during a fiscal control.
212 $conf->global->INVOICE_DISABLE_REPLACEMENT = 1;
213 }
214 if ($fmysoc->country_code == 'GR' && !isset($conf->global->INVOICE_DISABLE_REPLACEMENT)) {
215 // The replacement invoice type is not allowed in Greece.
216 $conf->global->INVOICE_DISABLE_REPLACEMENT = 1;
217 }
218 if ($fmysoc->country_code == 'GR' && !isset($conf->global->INVOICE_DISABLE_DEPOSIT)) {
219 // The deposit invoice type is not allowed in Greece.
220 $conf->global->INVOICE_DISABLE_DEPOSIT = 1;
221 }
222
223 if (($fmysoc->localtax1_assuj || $fmysoc->localtax2_assuj) && !isset($conf->global->MAIN_NO_INPUT_PRICE_WITH_TAX)) {
224 // For countries using the 2nd or 3rd tax, we disable input/edit of lines using the price including tax (because 2nb and 3rd tax not yet taken into account).
225 // Work In Progress to support all taxes into unit price entry when MAIN_UNIT_PRICE_WITH_TAX_IS_FOR_ALL_TAXES is set.
226 $conf->global->MAIN_NO_INPUT_PRICE_WITH_TAX = 1;
227 }
228 // Set also the global variable $mysoc
229 global $mysoc;
230 $mysoc = $fmysoc;
231
232 // Reload langs
233 $langcode = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
234 if (!empty($user->conf->MAIN_LANG_DEFAULT)) {
235 $langcode = $user->conf->MAIN_LANG_DEFAULT;
236 }
237 if ($langs->getDefaultLang() != $langcode) {
238 $langs->setDefaultLang($langcode);
239 $langs->tab_translate = array();
240 $langs->loadLangs(array('main'));
241 }
242 }
243
244 if ($conf->entity != ($token_entity ? $token_entity : 1)) {
245 throw new RestException(401, "functions_isallowed::check_user_api_key Authentication KO for '".$login."': Token not valid (may be a typo or a wrong entity)");
246 }
247 } elseif ($nbrows > 1) {
248 throw new RestException(503, 'Error when fetching user api_key : More than 1 user with this apikey');
249 }
250 } else {
251 throw new RestException(503, 'Error when fetching user api_key :'.$this->db->error);
252 }
253
254 if ($login && $stored_key != $api_key) { // This should not happen since we did a search on api_key
255 $userClass::setCacheIdentifier($api_key);
256 return false;
257 }
258
259 $genericmessageerroruser = 'Error user not valid (not found with api key or bad status or bad validity dates) (conf->entity='.$conf->entity.')';
260
261 if (!$login) {
262 dol_syslog("functions_isallowed::check_user_api_key Authentication KO for api key: Error when searching login user from api key", LOG_NOTICE);
263 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
264 throw new RestException(401, $genericmessageerroruser);
265 }
266
267 $fuser = new User($this->db);
268 $result = $fuser->fetch(0, $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)
269 if ($result <= 0) {
270 dol_syslog("functions_isallowed::check_user_api_key Authentication KO for '".$login."': Failed to fetch on entity", LOG_NOTICE);
271 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
272 throw new RestException(401, $genericmessageerroruser);
273 }
274
275 // Check if user status is enabled
276 if ($fuser->status != $fuser::STATUS_ENABLED) {
277 // Status is disabled
278 dol_syslog("functions_isallowed::check_user_api_key Authentication KO for '".$login."': The user has been disabled", LOG_NOTICE);
279 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
280 throw new RestException(401, $genericmessageerroruser);
281 }
282
283 // Check if session was unvalidated by a password change
284 if (($fuser->flagdelsessionsbefore && !empty($_SESSION["dol_logindate"]) && $fuser->flagdelsessionsbefore > $_SESSION["dol_logindate"])) {
285 // Session is no more valid
286 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.");
287 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
288 throw new RestException(401, $genericmessageerroruser);
289 }
290
291 // Check date validity
292 if ($fuser->isNotIntoValidityDateRange()) {
293 // User validity dates are no more valid
294 dol_syslog("functions_isallowed::check_user_api_key Authentication KO for '".$login."': The user login has a validity between [".$fuser->datestartvalidity." and ".$fuser->dateendvalidity."], current date is ".dol_now());
295 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
296 throw new RestException(401, $genericmessageerroruser);
297 }
298
299 // Increase counter of API access
300 if (getDolGlobalString('API_COUNTER_ENABLED')) {
301 if (!getDolGlobalString('API_IN_TOKEN_TABLE')) {
302 // Update the counter into table llx_const
303 include DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
304 dolibarr_set_const($this->db, 'API_COUNTER_COUNT', getDolGlobalInt('API_COUNTER_COUNT') + 1);
305 //var_dump('eeee');exit;
306 } else {
307 // Update the counter into table llx_oauth_token
308 $tmpnow = dol_getdate(dol_now('gmt'), true, 'gmt');
309
310 $sqlforcounter = "UPDATE ".$this->db->prefix()."oauth_token SET ";
311 $sqlforcounter .= " apicount_total = apicount_total + 1,";
312 $sqlforcounter .= " apicount_month = apicount_month + 1,";
313 // if last access was done during previous month, we save pageview_month into pageviews_previous_month
314 $sqlforcounter .= " pageviews_previous_month = ".$this->db->ifsql("lastaccess < '".$this->db->idate(dol_mktime(0, 0, 0, $tmpnow['mon'], 1, $tmpnow['year'], 'gmt', 0), 'gmt')."'", 'apicount_month', 'apicount_previous_month').",";
315 $sqlforcounter .= " lastaccess = '".$this->db->idate(dol_now('gmt'), 'gmt')."'";
316 $sqlforcounter .= " WHERE rowid = ".((int) $token_rowid);
317
318 $this->db->query($sqlforcounter);
319 }
320 }
321
322 // User seems valid
323 $fuser->loadRights();
324
325 // Set the property $user to the $user of API
326 static::$user = $fuser;
327
328 // Set also the global variable $user to the $user of API
329 $user = $fuser;
330
331 if ($fuser->socid) {
332 static::$role = 'external';
333 }
334
335 if ($fuser->admin) {
336 static::$role = 'admin';
337 }
338 } else {
339 throw new RestException(401, "Failed to login to API. Neither parameter 'HTTP_DOLAPIKEY' nor 'Authentication: Bearer' found on HTTP header (and no parameter DOLAPIKEY in URL).");
340 }
341
342 $userClass::setCacheIdentifier(static::$role);
343 Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess';
344 $requirefortest = static::$requires;
345 if (!is_array($requirefortest)) {
346 $requirefortest = explode(',', $requirefortest);
347 }
348 return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin';
349 }
350
351 // phpcs:disable PEAR.NamingConventions.ValidFunctionName
356 {
357 // phpcs:enable
358 return '';
359 }
360
369 public static function verifyAccess(array $m)
370 {
371 $requires = isset($m['class']['DolibarrApiAccess']['properties']['requires'])
372 ? $m['class']['DolibarrApiAccess']['properties']['requires']
373 : false;
374
375
376 return $requires
377 ? static::$role == 'admin' || in_array(static::$role, (array) $requires)
378 : true;
379 }
380}
dolibarr_set_const($db, $name, $value, $type='chaine', $visible=0, $note='', $entity=1)
Insert a parameter (key,value) into database (delete old key then insert it again).
Dolibarr API access class.
__construct()
Constructor.
__isAllowed()
Check access.
static verifyAccess(array $m)
Verify access.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage Dolibarr users.
global $mysoc
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_string_nounprintableascii($str, $removetabcrlf=1)
Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F).
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
dolEncrypt($chain, $key='', $ciphering='', $forceseed='')
Encode a string with a symmetric encryption.
dolDecrypt($chain, $key='')
Decode a string with a symmetric encryption.