dolibarr 20.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 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
49class DolibarrApiAccess implements iAuthenticate
50{
51 const REALM = 'Restricted Dolibarr API';
52
56 public $db;
57
61 public static $requires = array('user', 'external', 'admin');
62
66 public static $role = 'user';
67
71 public static $user = null;
72
73
77 public function __construct()
78 {
79 global $db;
80 $this->db = $db;
81 }
82
83 // phpcs:disable PEAR.NamingConventions.ValidFunctionName
92 public function __isAllowed()
93 {
94 // phpcs:enable
95 global $conf, $db, $langs, $mysoc, $user;
96
97 $login = '';
98 $stored_key = '';
99
100 $userClass = Defaults::$userIdentifierClass;
101
102 /*foreach ($_SERVER as $key => $val)
103 {
104 dol_syslog($key.' - '.$val);
105 }*/
106
107 // api key can be provided in url with parameter api_key=xxx or ni header with header DOLAPIKEY:xxx
108 $api_key = '';
109 if (isset($_GET['api_key'])) { // For backward compatibility. Keep $_GET here.
110 // TODO Add option to disable use of api key on url. Return errors if used.
111 $api_key = $_GET['api_key'];
112 }
113 if (isset($_GET['DOLAPIKEY'])) {
114 // TODO Add option to disable use of api key on url. Return errors if used.
115 $api_key = $_GET['DOLAPIKEY']; // With GET method
116 }
117 if (isset($_SERVER['HTTP_DOLAPIKEY'])) { // Param DOLAPIKEY in header can be read with HTTP_DOLAPIKEY
118 $api_key = $_SERVER['HTTP_DOLAPIKEY']; // With header method (recommended)
119 }
120
121 $api_key = dol_string_nounprintableascii($api_key);
122
123 if (preg_match('/^dolcrypt:/i', $api_key)) {
124 throw new RestException(503, 'Bad value for the API key. An API key should not start with dolcrypt:');
125 }
126
127 if ($api_key) {
128 $userentity = 0;
129
130 $sql = "SELECT u.login, u.datec, u.api_key,";
131 $sql .= " u.tms as date_modification, u.entity";
132 $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
133 $sql .= " WHERE u.api_key = '".$this->db->escape($api_key)."' OR u.api_key = '".$this->db->escape(dolEncrypt($api_key, '', '', 'dolibarr'))."'";
134
135 $result = $this->db->query($sql);
136 if ($result) {
137 $nbrows = $this->db->num_rows($result);
138 if ($nbrows == 1) {
139 $obj = $this->db->fetch_object($result);
140 $login = $obj->login;
141 $stored_key = dolDecrypt($obj->api_key);
142 $userentity = $obj->entity;
143
144 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
145 $conf->entity = ($obj->entity ? $obj->entity : 1);
146 // We must also reload global conf to get params from the entity
147 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);
148 $conf->setValues($this->db);
149
150 // set global mysoc after setting conf entity (the entity can be changed with the user logged)
151 // see master.inc.php
152 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
153
154 $fmysoc = new Societe($db);
155 $fmysoc->setMysoc($conf);
156
157 // We set some specific default values according to country
158 if ($fmysoc->country_code == 'DE' && !isset($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) {
159 // For DE, we need to invert our address with customer address
160 $conf->global->MAIN_INVERT_SENDER_RECIPIENT = 1;
161 }
162 if ($fmysoc->country_code == 'FR' && !isset($conf->global->INVOICE_CATEGORY_OF_OPERATION)) {
163 // For FR, default value of option to show category of operations is on by default. Decret n°2099-1299 2022-10-07
164 $conf->global->INVOICE_CATEGORY_OF_OPERATION = 1;
165 }
166 if ($fmysoc->country_code == 'FR' && !isset($conf->global->INVOICE_DISABLE_REPLACEMENT)) {
167 // For FR, the replacement invoice type is not allowed.
168 // From an accounting point of view, this creates holes in the numbering of the invoice.
169 // This is very problematic during a fiscal control.
170 $conf->global->INVOICE_DISABLE_REPLACEMENT = 1;
171 }
172 if ($fmysoc->country_code == 'GR' && !isset($conf->global->INVOICE_DISABLE_REPLACEMENT)) {
173 // The replacement invoice type is not allowed in Greece.
174 $conf->global->INVOICE_DISABLE_REPLACEMENT = 1;
175 }
176 if ($fmysoc->country_code == 'GR' && !isset($conf->global->INVOICE_DISABLE_DEPOSIT)) {
177 // The deposit invoice type is not allowed in Greece.
178 $conf->global->INVOICE_DISABLE_DEPOSIT = 1;
179 }
180
181 if (($fmysoc->localtax1_assuj || $fmysoc->localtax2_assuj) && !isset($conf->global->MAIN_NO_INPUT_PRICE_WITH_TAX)) {
182 // 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).
183 // Work In Progress to support all taxes into unit price entry when MAIN_UNIT_PRICE_WITH_TAX_IS_FOR_ALL_TAXES is set.
184 $conf->global->MAIN_NO_INPUT_PRICE_WITH_TAX = 1;
185 }
186 // Set also the global variable $mysoc
187 $mysoc = $fmysoc;
188
189 // Reload langs
190 $langcode = (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT);
191 if (!empty($user->conf->MAIN_LANG_DEFAULT)) {
192 $langcode = $user->conf->MAIN_LANG_DEFAULT;
193 }
194 if ($langs->getDefaultLang() != $langcode) {
195 $langs->setDefaultLang($langcode);
196 $langs->tab_translate = array();
197 $langs->loadLangs(array('main'));
198 }
199 }
200 } elseif ($nbrows > 1) {
201 throw new RestException(503, 'Error when fetching user api_key : More than 1 user with this apikey');
202 }
203 } else {
204 throw new RestException(503, 'Error when fetching user api_key :'.$this->db->error_msg);
205 }
206
207 if ($login && $stored_key != $api_key) { // This should not happen since we did a search on api_key
208 $userClass::setCacheIdentifier($api_key);
209 return false;
210 }
211
212 $genericmessageerroruser = 'Error user not valid (not found with api key or bad status or bad validity dates) (conf->entity='.$conf->entity.')';
213
214 if (!$login) {
215 dol_syslog("functions_isallowed::check_user_api_key Authentication KO for api key: Error when searching login user from api key", LOG_NOTICE);
216 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
217 throw new RestException(401, $genericmessageerroruser);
218 }
219
220 $fuser = new User($this->db);
221 $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)
222 if ($result <= 0) {
223 dol_syslog("functions_isallowed::check_user_api_key Authentication KO for '".$login."': Failed to fetch on entity", LOG_NOTICE);
224 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
225 throw new RestException(401, $genericmessageerroruser);
226 }
227
228 // Check if user status is enabled
229 if ($fuser->status != $fuser::STATUS_ENABLED) {
230 // Status is disabled
231 dol_syslog("functions_isallowed::check_user_api_key Authentication KO for '".$login."': The user has been disabled", LOG_NOTICE);
232 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
233 throw new RestException(401, $genericmessageerroruser);
234 }
235
236 // Check if session was unvalidated by a password change
237 if (($fuser->flagdelsessionsbefore && !empty($_SESSION["dol_logindate"]) && $fuser->flagdelsessionsbefore > $_SESSION["dol_logindate"])) {
238 // Session is no more valid
239 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.");
240 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
241 throw new RestException(401, $genericmessageerroruser);
242 }
243
244 // Check date validity
245 if ($fuser->isNotIntoValidityDateRange()) {
246 // User validity dates are no more valid
247 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());
248 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
249 throw new RestException(401, $genericmessageerroruser);
250 }
251
252 // TODO
253 // Increase counter of API access
254 if (getDolGlobalString('API_COUNTER_ENABLED')) {
255 include DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
256 dolibarr_set_const($this->db, 'API_COUNTER_COUNT', getDolGlobalInt('API_COUNTER_COUNT') + 1);
257 //var_dump('eeee');exit;
258 }
259
260 // User seems valid
261 $fuser->getrights();
262
263 // Set the property $user to the $user of API
264 static::$user = $fuser;
265
266 // Set also the global variable $user to the $user of API
267 $user = $fuser;
268
269 if ($fuser->socid) {
270 static::$role = 'external';
271 }
272
273 if ($fuser->admin) {
274 static::$role = 'admin';
275 }
276 } else {
277 throw new RestException(401, "Failed to login to API. No parameter 'HTTP_DOLAPIKEY' on HTTP header (and no parameter DOLAPIKEY in URL).");
278 }
279
280 $userClass::setCacheIdentifier(static::$role);
281 Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess';
282 $requirefortest = static::$requires;
283 if (!is_array($requirefortest)) {
284 $requirefortest = explode(',', $requirefortest);
285 }
286 return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin';
287 }
288
289 // phpcs:disable PEAR.NamingConventions.ValidFunctionName
294 {
295 // phpcs:enable
296 return '';
297 }
298
307 public static function verifyAccess(array $m)
308 {
309 $requires = isset($m['class']['DolibarrApiAccess']['properties']['requires'])
310 ? $m['class']['DolibarrApiAccess']['properties']['requires']
311 : false;
312
313
314 return $requires
315 ? static::$role == 'admin' || in_array(static::$role, (array) $requires)
316 : true;
317 }
318}
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 dolibarr global constant string value.
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 symmetric encryption.
dolDecrypt($chain, $key='')
Decode a string with a symmetric encryption.