dolibarr 22.0.5
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, $db, $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
136 $sql = "SELECT u.login, u.datec, u.api_key,";
137 $sql .= " u.tms as date_modification, u.entity";
138 $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
139 $sql .= " WHERE u.api_key = '".$this->db->escape($api_key)."' OR u.api_key = '".$this->db->escape(dolEncrypt($api_key, '', '', 'dolibarr'))."'";
140
141 $result = $this->db->query($sql);
142 if ($result) {
143 $nbrows = $this->db->num_rows($result);
144 if ($nbrows == 1) {
145 $obj = $this->db->fetch_object($result);
146 $login = $obj->login;
147 $stored_key = dolDecrypt($obj->api_key);
148 $userentity = $obj->entity;
149
150 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
151 $conf->entity = ($obj->entity ? $obj->entity : 1);
152 // We must also reload global conf to get params from the entity
153 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);
154 $conf->setValues($this->db);
155
156 // set global mysoc after setting conf entity (the entity can be changed with the user logged)
157 // see master.inc.php
158 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
159
160 $fmysoc = new Societe($db);
161 $fmysoc->setMysoc($conf);
162
163 // We set some specific default values according to country
164 if ($fmysoc->country_code == 'DE' && !isset($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) {
165 // For DE, we need to invert our address with customer address
166 $conf->global->MAIN_INVERT_SENDER_RECIPIENT = 1;
167 }
168 if ($fmysoc->country_code == 'FR' && !isset($conf->global->INVOICE_CATEGORY_OF_OPERATION)) {
169 // For FR, default value of option to show category of operations is on by default. Decret n°2099-1299 2022-10-07
170 $conf->global->INVOICE_CATEGORY_OF_OPERATION = 1;
171 }
172 if ($fmysoc->country_code == 'FR' && !isset($conf->global->INVOICE_DISABLE_REPLACEMENT)) {
173 // For FR, the replacement invoice type is not allowed.
174 // From an accounting point of view, this creates holes in the numbering of the invoice.
175 // This is very problematic during a fiscal control.
176 $conf->global->INVOICE_DISABLE_REPLACEMENT = 1;
177 }
178 if ($fmysoc->country_code == 'GR' && !isset($conf->global->INVOICE_DISABLE_REPLACEMENT)) {
179 // The replacement invoice type is not allowed in Greece.
180 $conf->global->INVOICE_DISABLE_REPLACEMENT = 1;
181 }
182 if ($fmysoc->country_code == 'GR' && !isset($conf->global->INVOICE_DISABLE_DEPOSIT)) {
183 // The deposit invoice type is not allowed in Greece.
184 $conf->global->INVOICE_DISABLE_DEPOSIT = 1;
185 }
186
187 if (($fmysoc->localtax1_assuj || $fmysoc->localtax2_assuj) && !isset($conf->global->MAIN_NO_INPUT_PRICE_WITH_TAX)) {
188 // 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).
189 // Work In Progress to support all taxes into unit price entry when MAIN_UNIT_PRICE_WITH_TAX_IS_FOR_ALL_TAXES is set.
190 $conf->global->MAIN_NO_INPUT_PRICE_WITH_TAX = 1;
191 }
192 // Set also the global variable $mysoc
193 global $mysoc;
194 $mysoc = $fmysoc;
195
196 // Reload langs
197 $langcode = (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT);
198 if (!empty($user->conf->MAIN_LANG_DEFAULT)) {
199 $langcode = $user->conf->MAIN_LANG_DEFAULT;
200 }
201 if ($langs->getDefaultLang() != $langcode) {
202 $langs->setDefaultLang($langcode);
203 $langs->tab_translate = array();
204 $langs->loadLangs(array('main'));
205 }
206 }
207 } elseif ($nbrows > 1) {
208 throw new RestException(503, 'Error when fetching user api_key : More than 1 user with this apikey');
209 }
210 } else {
211 throw new RestException(503, 'Error when fetching user api_key :'.$this->db->error);
212 }
213
214 if ($login && $stored_key != $api_key) { // This should not happen since we did a search on api_key
215 $userClass::setCacheIdentifier($api_key);
216 return false;
217 }
218
219 $genericmessageerroruser = 'Error user not valid (not found with api key or bad status or bad validity dates) (conf->entity='.$conf->entity.')';
220
221 if (!$login) {
222 dol_syslog("functions_isallowed::check_user_api_key Authentication KO for api key: Error when searching login user from api key", LOG_NOTICE);
223 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
224 throw new RestException(401, $genericmessageerroruser);
225 }
226
227 $fuser = new User($this->db);
228 $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)
229 if ($result <= 0) {
230 dol_syslog("functions_isallowed::check_user_api_key Authentication KO for '".$login."': Failed to fetch on entity", LOG_NOTICE);
231 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
232 throw new RestException(401, $genericmessageerroruser);
233 }
234
235 // Check if user status is enabled
236 if ($fuser->status != $fuser::STATUS_ENABLED) {
237 // Status is disabled
238 dol_syslog("functions_isallowed::check_user_api_key Authentication KO for '".$login."': The user has been disabled", LOG_NOTICE);
239 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
240 throw new RestException(401, $genericmessageerroruser);
241 }
242
243 // Check if session was unvalidated by a password change
244 if (($fuser->flagdelsessionsbefore && !empty($_SESSION["dol_logindate"]) && $fuser->flagdelsessionsbefore > $_SESSION["dol_logindate"])) {
245 // Session is no more valid
246 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.");
247 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
248 throw new RestException(401, $genericmessageerroruser);
249 }
250
251 // Check date validity
252 if ($fuser->isNotIntoValidityDateRange()) {
253 // User validity dates are no more valid
254 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());
255 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
256 throw new RestException(401, $genericmessageerroruser);
257 }
258
259 // TODO
260 // Increase counter of API access
261 if (getDolGlobalString('API_COUNTER_ENABLED')) {
262 include DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
263 dolibarr_set_const($this->db, 'API_COUNTER_COUNT', getDolGlobalInt('API_COUNTER_COUNT') + 1);
264 //var_dump('eeee');exit;
265 }
266
267 // User seems valid
268 $fuser->loadRights();
269
270 // Set the property $user to the $user of API
271 static::$user = $fuser;
272
273 // Set also the global variable $user to the $user of API
274 $user = $fuser;
275
276 if ($fuser->socid) {
277 static::$role = 'external';
278 }
279
280 if ($fuser->admin) {
281 static::$role = 'admin';
282 }
283 } else {
284 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).");
285 }
286
287 $userClass::setCacheIdentifier(static::$role);
288 Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess';
289 $requirefortest = static::$requires;
290 if (!is_array($requirefortest)) {
291 $requirefortest = explode(',', $requirefortest);
292 }
293 return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin';
294 }
295
296 // phpcs:disable PEAR.NamingConventions.ValidFunctionName
301 {
302 // phpcs:enable
303 return '';
304 }
305
314 public static function verifyAccess(array $m)
315 {
316 $requires = isset($m['class']['DolibarrApiAccess']['properties']['requires'])
317 ? $m['class']['DolibarrApiAccess']['properties']['requires']
318 : false;
319
320
321 return $requires
322 ? static::$role == 'admin' || in_array(static::$role, (array) $requires)
323 : true;
324 }
325}
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.
dol_now($mode='auto')
Return date for now.
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.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
dolEncrypt($chain, $key='', $ciphering='', $forceseed='')
Encode a string with a symmetric encryption.
dolDecrypt($chain, $key='')
Decode a string with a symmetric encryption.