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