dolibarr 25.0.0-alpha
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-2026 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']) || isset($_GET['DOLAPIKEY'])) {
109 // A key passed in the query string ends up in the web server access log, in proxy logs, in the
110 // browser history and in the Referer header of any outgoing link. Setting API_DISABLE_KEY_IN_URL
111 // refuses it instead of accepting it, so that a client still using that form is corrected rather
112 // than leaking the key silently. Off by default, for backward compatibility.
113 if (getDolGlobalString('API_DISABLE_KEY_IN_URL')) {
114 throw new RestException(401, 'The API key must be sent in the DOLAPIKEY header, not in the URL (API_DISABLE_KEY_IN_URL is set)');
115 }
116 }
117 if (isset($_GET['api_key'])) { // For backward compatibility. Keep $_GET here.
118 $api_key = $_GET['api_key'];
119 }
120 if (isset($_GET['DOLAPIKEY'])) {
121 $api_key = $_GET['DOLAPIKEY']; // With GET method
122 }
123
124 // TODO Can filter on user agent.
125 //$api_useragent = $_SERVER['HTTP_USER_AGENT'];
126
127 if (isset($_SERVER['HTTP_DOLAPIKEY'])) { // HTTP Header entry "DOLAPIKEY: ..." can be read with $_SERVER["HTTP_DOLAPIKEY"]
128 $api_key = $_SERVER['HTTP_DOLAPIKEY']; // With header method (recommended)
129 } elseif (empty($api_key)) {
130 $headers = getallheaders(); // HTTP Header entry "Authorization: Bearer ..." can be read with getallheaders
131 $api_key = preg_replace('/^Bearer\s+/i', '', empty($headers['Authorization']) ? '' : $headers['Authorization']);
132 };
133
134 $api_key = dol_string_nounprintableascii($api_key, 1);
135
136 if (preg_match('/^dolcrypt:/i', $api_key)) {
137 throw new RestException(503, 'Bad value for the API key. An API key should not start with dolcrypt:');
138 }
139
140 if ($api_key) {
141 $userentity = 0;
142 $token_rowid = 0;
143
144 if (!getDolGlobalString('API_IN_TOKEN_TABLE')) {
145 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE') && defined("DOLENTITY")) {
146 $sql = "SELECT DISTINCT u.login, u.datec, u.api_key as use_api, u.api_key as api_key, 0 as token_rowid,";
147 $sql .= " u.tms as date_modification,";
148 $sql .= " gu.entity, gu.entity as token_entity";
149 $sql .= " FROM ".$this->db->prefix()."user as u";
150 $sql .= " JOIN ".$this->db->prefix()."usergroup_user as gu ON u.rowid = gu.fk_user AND gu.entity = ".((int) $conf->entity);
151 $sql .= " WHERE u.api_key = '".$this->db->escape($api_key)."' OR u.api_key = '".$this->db->escape(dolEncrypt($api_key, '', '', 'dolibarr'))."'";
152 } else {
153 $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,";
154 $sql .= " u.tms as date_modification";
155 $sql .= " FROM ".$this->db->prefix()."user as u";
156 $sql .= " WHERE u.api_key = '".$this->db->escape($api_key)."' OR u.api_key = '".$this->db->escape(dolEncrypt($api_key, '', '', 'dolibarr'))."'";
157 }
158 } else {
159 if (isModEnabled('multicompany') && getDolGlobalString('MULTICOMPANY_TRANSVERSE_MODE') && defined("DOLENTITY")) {
160 $sql = "SELECT DISTINCT u.login, u.datec, u.api_key as use_api, oat.tokenstring as api_key, oat.entity as token_entity, oat.rowid as token_rowid,";
161 $sql .= " oat.tms as date_modification,";
162 $sql .= " gu.entity";
163 $sql .= " FROM ".$this->db->prefix()."oauth_token AS oat";
164 $sql .= " JOIN ".$this->db->prefix()."user AS u ON u.rowid = oat.fk_user";
165 $sql .= " JOIN ".$this->db->prefix()."usergroup_user as gu ON u.rowid = gu.fk_user AND gu.entity = ".((int) $conf->entity);
166 $sql .= " WHERE (oat.tokenstring = '".$this->db->escape($api_key)."'";
167 $sql .= " OR oat.tokenstring = '".$this->db->escape(dolEncrypt($api_key, '', '', 'dolibarr'))."')";
168 $sql .= " AND gu.entity = oat.entity";
169 $sql .= " AND oat.service = 'dolibarr_rest_api'";
170 } else {
171 $sql = "SELECT u.login, u.datec, u.api_key as use_api, u.entity, oat.tokenstring as api_key, oat.entity as token_entity, oat.rowid as token_rowid,";
172 $sql .= " oat.tms as date_modification";
173 $sql .= " FROM ".$this->db->prefix()."oauth_token AS oat";
174 $sql .= " JOIN ".$this->db->prefix()."user AS u ON u.rowid = oat.fk_user";
175 $sql .= " WHERE (oat.tokenstring = '".$this->db->escape($api_key)."'";
176 $sql .= " OR oat.tokenstring = '".$this->db->escape(dolEncrypt($api_key, '', '', 'dolibarr'))."')";
177 $sql .= " AND oat.service = 'dolibarr_rest_api'";
178 }
179 }
180
181 $result = $this->db->query($sql);
182 if ($result) {
183 $nbrows = $this->db->num_rows($result);
184 if ($nbrows == 1) {
185 $obj = $this->db->fetch_object($result);
186
187 $login = $obj->login;
188 $stored_key = dolDecrypt($obj->api_key);
189 $userentity = $obj->entity;
190 $token_entity = $obj->token_entity;
191 $token_rowid = $obj->token_rowid;
192
193 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
194 $conf->entity = ($obj->entity ? $obj->entity : 1);
195 // We must also reload global conf to get params from the entity
196 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);
197 $conf->setValues($this->db);
198
199 // set global mysoc after setting conf entity (the entity can be changed with the user logged)
200 // see master.inc.php
201 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
202
203 $fmysoc = new Societe($this->db);
204 $fmysoc->setMysoc($conf);
205
206 // We set some specific default values according to country
207 if ($fmysoc->country_code == 'DE' && !isset($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) {
208 // For DE, we need to invert our address with customer address
209 $conf->global->MAIN_INVERT_SENDER_RECIPIENT = 1;
210 }
211 if ($fmysoc->country_code == 'FR' && !isset($conf->global->INVOICE_CATEGORY_OF_OPERATION)) {
212 // For FR, default value of option to show category of operations is on by default. Decret n°2099-1299 2022-10-07
213 $conf->global->INVOICE_CATEGORY_OF_OPERATION = 1;
214 }
215 if ($fmysoc->country_code == 'FR' && !isset($conf->global->INVOICE_DISABLE_REPLACEMENT)) {
216 // For FR, the replacement invoice type is not allowed.
217 // From an accounting point of view, this creates holes in the numbering of the invoice.
218 // This is very problematic during a fiscal control.
219 $conf->global->INVOICE_DISABLE_REPLACEMENT = 1;
220 }
221 if ($fmysoc->country_code == 'GR' && !isset($conf->global->INVOICE_DISABLE_REPLACEMENT)) {
222 // The replacement invoice type is not allowed in Greece.
223 $conf->global->INVOICE_DISABLE_REPLACEMENT = 1;
224 }
225 if ($fmysoc->country_code == 'GR' && !isset($conf->global->INVOICE_DISABLE_DEPOSIT)) {
226 // The deposit invoice type is not allowed in Greece.
227 $conf->global->INVOICE_DISABLE_DEPOSIT = 1;
228 }
229
230 if (($fmysoc->localtax1_assuj || $fmysoc->localtax2_assuj) && !isset($conf->global->MAIN_NO_INPUT_PRICE_WITH_TAX)) {
231 // 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).
232 // Work In Progress to support all taxes into unit price entry when MAIN_UNIT_PRICE_WITH_TAX_IS_FOR_ALL_TAXES is set.
233 $conf->global->MAIN_NO_INPUT_PRICE_WITH_TAX = 1;
234 }
235 // Set also the global variable $mysoc
236 global $mysoc;
237 $mysoc = $fmysoc;
238
239 // Reload langs
240 $langcode = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
241 if (!empty($user->conf->MAIN_LANG_DEFAULT)) {
242 $langcode = $user->conf->MAIN_LANG_DEFAULT;
243 }
244 if ($langs->getDefaultLang() != $langcode) {
245 $langs->setDefaultLang($langcode);
246 $langs->tab_translate = array();
247 $langs->loadLangs(array('main'));
248 }
249 }
250
251 if ($conf->entity != ($token_entity ? $token_entity : 1)) {
252 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)");
253 }
254 } elseif ($nbrows > 1) {
255 throw new RestException(503, 'Error when fetching user api_key : More than 1 user with this apikey');
256 }
257 } else {
258 throw new RestException(503, 'Error when fetching user api_key :'.$this->db->lasterror());
259 }
260
261 if ($login && $stored_key != $api_key) { // This should not happen since we did a search on api_key
262 $userClass::setCacheIdentifier($api_key);
263 return false;
264 }
265
266 $genericmessageerroruser = 'Error user not valid (not found with api key or bad status or bad validity dates) (conf->entity='.$conf->entity.')';
267
268 if (!$login) {
269 dol_syslog("functions_isallowed::check_user_api_key Authentication KO for api key: Error when searching login user from api key", LOG_NOTICE);
270 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
271 throw new RestException(401, $genericmessageerroruser);
272 }
273
274 $fuser = new User($this->db);
275 $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)
276 if ($result <= 0) {
277 dol_syslog("functions_isallowed::check_user_api_key Authentication KO for '".$login."': Failed to fetch on entity", LOG_NOTICE);
278 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
279 throw new RestException(401, $genericmessageerroruser);
280 }
281
282 // Check if user status is enabled
283 if ($fuser->status != $fuser::STATUS_ENABLED) {
284 // Status is disabled
285 dol_syslog("functions_isallowed::check_user_api_key Authentication KO for '".$login."': The user has been disabled", LOG_NOTICE);
286 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
287 throw new RestException(401, $genericmessageerroruser);
288 }
289
290 // Check if session was unvalidated by a password change
291 if (($fuser->flagdelsessionsbefore && !empty($_SESSION["dol_logindate"]) && $fuser->flagdelsessionsbefore > $_SESSION["dol_logindate"])) {
292 // Session is no more valid
293 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.");
294 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
295 throw new RestException(401, $genericmessageerroruser);
296 }
297
298 // Check date validity
299 if ($fuser->isNotIntoValidityDateRange()) {
300 // User validity dates are no more valid
301 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());
302 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
303 throw new RestException(401, $genericmessageerroruser);
304 }
305
306 // Increase counter of API access
307 if (getDolGlobalString('API_COUNTER_ENABLED')) {
308 if (!getDolGlobalString('API_IN_TOKEN_TABLE')) {
309 // Update the counter into table llx_const
310 include DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
311 dolibarr_set_const($this->db, 'API_COUNTER_COUNT', getDolGlobalInt('API_COUNTER_COUNT') + 1);
312 //var_dump('eeee');exit;
313 } else {
314 // Update the counter into table llx_oauth_token
315 $tmpnow = dol_getdate(dol_now('gmt'), true, 'gmt');
316
317 $sqlforcounter = "UPDATE ".$this->db->prefix()."oauth_token SET ";
318 $sqlforcounter .= " apicount_total = apicount_total + 1,";
319 $sqlforcounter .= " apicount_month = apicount_month + 1,";
320 // if last access was done during previous month, we save apicount_month into apicount_previous_month
321 $sqlforcounter .= " apicount_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').",";
322 $sqlforcounter .= " lastaccess = '".$this->db->idate(dol_now('gmt'), 'gmt')."'";
323 $sqlforcounter .= " WHERE rowid = ".((int) $token_rowid);
324
325 $this->db->query($sqlforcounter);
326 }
327 }
328
329 // User seems valid
330 $fuser->loadRights();
331
332 // Set the property $user to the $user of API
333 static::$user = $fuser;
334
335 // Set also the global variable $user to the $user of API
336 $user = $fuser;
337
338 if ($fuser->socid) {
339 static::$role = 'external';
340 }
341
342 if ($fuser->admin) {
343 static::$role = 'admin';
344 }
345 } else {
346 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).");
347 }
348
349 $userClass::setCacheIdentifier(static::$role);
350
351 Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess';
352 $requirefortest = static::$requires;
353 if (!is_array($requirefortest)) {
354 $requirefortest = explode(',', $requirefortest);
355 }
356 return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin';
357 }
358
359 // phpcs:disable PEAR.NamingConventions.ValidFunctionName
364 {
365 // phpcs:enable
366 return '';
367 }
368
377 public static function verifyAccess(array $m)
378 {
379 $requires = isset($m['class']['DolibarrApiAccess']['properties']['requires'])
380 ? $m['class']['DolibarrApiAccess']['properties']['requires']
381 : false;
382
383
384 return $requires
385 ? static::$role == 'admin' || in_array(static::$role, (array) $requires)
386 : true;
387 }
388}
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)
Check that the role of user is among a the given list defined into static\$requires.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage Dolibarr users.
global $mysoc
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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.
dolDecrypt($chain, $key='', $patterntotest='')
Decode a string with a symmetric encryption.
dolEncrypt($chain, $key='', $ciphering='', $forceseed='', $obfuscationmode='dolcrypt')
Encode a string with a symmetric encryption.