dolibarr 20.0.0
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, $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 } elseif ($nbrows > 1) {
151 throw new RestException(503, 'Error when fetching user api_key : More than 1 user with this apikey');
152 }
153 } else {
154 throw new RestException(503, 'Error when fetching user api_key :'.$this->db->error_msg);
155 }
156
157 if ($login && $stored_key != $api_key) { // This should not happen since we did a search on api_key
158 $userClass::setCacheIdentifier($api_key);
159 return false;
160 }
161
162 $genericmessageerroruser = 'Error user not valid (not found with api key or bad status or bad validity dates) (conf->entity='.$conf->entity.')';
163
164 if (!$login) {
165 dol_syslog("functions_isallowed::check_user_api_key Authentication KO for api key: Error when searching login user from api key", LOG_NOTICE);
166 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
167 throw new RestException(401, $genericmessageerroruser);
168 }
169
170 $fuser = new User($this->db);
171 $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)
172 if ($result <= 0) {
173 dol_syslog("functions_isallowed::check_user_api_key Authentication KO for '".$login."': Failed to fetch on entity", LOG_NOTICE);
174 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
175 throw new RestException(401, $genericmessageerroruser);
176 }
177
178 // Check if user status is enabled
179 if ($fuser->statut != $fuser::STATUS_ENABLED) {
180 // Status is disabled
181 dol_syslog("functions_isallowed::check_user_api_key Authentication KO for '".$login."': The user has been disabled", LOG_NOTICE);
182 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
183 throw new RestException(401, $genericmessageerroruser);
184 }
185
186 // Check if session was unvalidated by a password change
187 if (($fuser->flagdelsessionsbefore && !empty($_SESSION["dol_logindate"]) && $fuser->flagdelsessionsbefore > $_SESSION["dol_logindate"])) {
188 // Session is no more valid
189 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.");
190 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
191 throw new RestException(401, $genericmessageerroruser);
192 }
193
194 // Check date validity
195 if ($fuser->isNotIntoValidityDateRange()) {
196 // User validity dates are no more valid
197 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());
198 sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
199 throw new RestException(401, $genericmessageerroruser);
200 }
201
202 // User seems valid
203 $fuser->getrights();
204
205 // Set the property $user to the $user of API
206 static::$user = $fuser;
207
208 // Set also the global variable $user to the $user of API
209 $user = $fuser;
210
211 if ($fuser->socid) {
212 static::$role = 'external';
213 }
214
215 if ($fuser->admin) {
216 static::$role = 'admin';
217 }
218 } else {
219 throw new RestException(401, "Failed to login to API. No parameter 'HTTP_DOLAPIKEY' on HTTP header (and no parameter DOLAPIKEY in URL).");
220 }
221
222 $userClass::setCacheIdentifier(static::$role);
223 Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess';
224 $requirefortest = static::$requires;
225 if (!is_array($requirefortest)) {
226 $requirefortest = explode(',', $requirefortest);
227 }
228 return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin';
229 }
230
231 // phpcs:disable PEAR.NamingConventions.ValidFunctionName
236 {
237 // phpcs:enable
238 return '';
239 }
240
249 public static function verifyAccess(array $m)
250 {
251 $requires = isset($m['class']['DolibarrApiAccess']['properties']['requires'])
252 ? $m['class']['DolibarrApiAccess']['properties']['requires']
253 : false;
254
255
256 return $requires
257 ? static::$role == 'admin' || in_array(static::$role, (array) $requires)
258 : true;
259 }
260}
Dolibarr API access class.
__construct()
Constructor.
__isAllowed()
Check access.
static verifyAccess(array $m)
Verify access.
Class to manage Dolibarr users.
dol_now($mode='auto')
Return date for now.
dol_string_nounprintableascii($str, $removetabcrlf=1)
Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F).
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.