dolibarr/htdocs/api/class/api_access.class.php

268 lines
9.8 KiB
PHP
Raw Permalink Normal View History

2015-05-02 18:14:51 +02:00
<?php
2015-05-06 01:25:56 +02:00
/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
* Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
2023-01-18 10:48:18 +01:00
* Copyright (C) 2023 Ferran Marcet <fmarcet@2byte.es>
* Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
2015-05-06 01:25:56 +02:00
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
2019-09-23 21:55:30 +02:00
* along with this program. If not, see <https://www.gnu.org/licenses/>.
2015-05-06 01:25:56 +02:00
*/
2015-05-02 18:14:51 +02:00
2015-11-22 17:17:06 +01:00
// Create the autoloader for Luracast
require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/AutoLoader.php';
call_user_func(
/**
* @return Luracast\Restler\AutoLoader
*/
static function () {
$loader = Luracast\Restler\AutoLoader::instance();
spl_autoload_register($loader);
return $loader;
}
);
2015-11-22 17:17:06 +01:00
require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/iAuthenticate.php';
require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/iUseAuthentication.php';
require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Resources.php';
require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Defaults.php';
require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/RestException.php';
2023-10-26 12:22:54 +02:00
2023-04-30 03:10:20 +02:00
use Luracast\Restler\iAuthenticate;
use Luracast\Restler\Resources;
use Luracast\Restler\Defaults;
use Luracast\Restler\RestException;
2015-05-02 18:14:51 +02:00
/**
2015-05-06 00:55:42 +02:00
* Dolibarr API access class
2015-05-02 18:14:51 +02:00
*
*/
class DolibarrApiAccess implements iAuthenticate
{
const REALM = 'Restricted Dolibarr API';
2015-05-12 16:42:35 +02:00
2023-08-06 01:26:06 +02:00
/**
* @var DoliDB Database handler
*/
public $db;
2015-05-02 18:14:51 +02:00
/**
2015-05-12 16:42:35 +02:00
* @var array $requires role required by API method user / external / admin
2015-05-02 18:14:51 +02:00
*/
public static $requires = array('user', 'external', 'admin');
2015-05-12 16:42:35 +02:00
/**
* @var string $role user role
*/
public static $role = 'user';
2015-05-12 16:42:35 +02:00
/**
2015-05-12 16:42:35 +02:00
* @var User $user Loggued user
*/
Fix #28071 - New branch to fix bad merge (#28083) * Merge branch 'develop' of git@github.com:Dolibarr/dolibarr.git into develop * Merge branch 'develop' of git@github.com:Dolibarr/dolibarr.git into develop * Qual: Introduce getDataToShowPhoto to prepare generic code * Merge branch 'develop' of git@github.com:Dolibarr/dolibarr.git into develop * Fix missing trans * Fix langs * Merge branch 'develop' of git@github.com:Dolibarr/dolibarr.git into develop * Remove useless files in web templates * Clean code * Fix duplicate translation key * Fix duplicate translation key * Merge branch 'develop' of git@github.com:Dolibarr/dolibarr.git into develop * Fix duplicate key * Fix $object * Debug v19 * WIP SMSing * Merge branch 'develop' of git@github.com:Dolibarr/dolibarr.git into develop * WIP EMAILINGS_SUPPORT_ALSO_SMS * Merge branch 'develop' of git@github.com:Dolibarr/dolibarr.git into develop * Merge branch 'develop' of git@github.com:Dolibarr/dolibarr.git into develop * WIP SMSing * Debug the "validate" feature * Merge branch 'develop' of git@github.com:Dolibarr/dolibarr.git into develop * Clean code * Move rights->x->y into hasRight('x', 'y') * Move rights->x->y into hasRight('x', 'y') * Move rights->x->y into hasRight('x', 'y') * Move rights->x->y into hasRight('x', 'y') * Move rights->x->y into hasRight('x', 'y') * Move rights->x->y into hasRight('x', 'y') * Merge branch 'develop' of git@github.com:Dolibarr/dolibarr.git into develop * Merge branch 'develop' of git@github.com:Dolibarr/dolibarr.git into develop * Enhance rector to fix empty($user->rights->modulex->perm1) * Merge branch 'develop' of git@github.com:Dolibarr/dolibarr.git into develop * Fix template to use v19 dev rules * Fix use v19 dev rules * Fix phpunit * Debug v19 * Clean code * Use rector to convert user->rights into user->hasRight * Clean code * Use rector to convert user->rights into user->hasRight * Use rector to convert user->rights into user->hasRight * Clean code * Fix phpcs * add editorconfig for sql files (#27999) Co-authored-by: Laurent Destailleur <eldy@destailleur.fr> * add model_pdf field in llx_ticket-ticket.sql (#27996) * add model_pdf field in llx_ticket-ticket.sql * Update 19.0.0-20.0.0.sql * Update 19.0.0-20.0.0.sql * Improve wording in README (#27994) * fix phpstan (#27989) * fix phpstan * Update UserRightsToFunction.php --------- Co-authored-by: Laurent Destailleur <eldy@destailleur.fr> * Qual: Fix spelling/working in datapolicy translations (#28006) # Qual: Fix spelling/wording in datapolicy translations Fixed some spelling and wording in datapolicy translations. * qual: phpstan for htdocs/ticket/class/ticketstats.class.php (#27986) htdocs/ticket/class/ticketstats.class.php 98 Parameter #1 $year (string) of method TicketStats::getNbByMonth() should be compatible with parameter $year (int) of method Stats::getNbByMonth() * Merge branch '19.0' of git@github.com:Dolibarr/dolibarr.git into develop * Fix user with readonly perm on email template must be able to read. * Fix doc * Merge branch 'develop' of git@github.com:Dolibarr/dolibarr.git into develop * Better message * Add missing fields in merge of thirdparty * Debug v19 selection of ticket printer per terminal * Merge branch 'develop' of git@github.com:Dolibarr/dolibarr.git into develop * Use constant * NEW: Adding a recipient on emails sent, change status to sent partialy. * fix travis (#28052) * fix travis * Update partnership.class.php * fix php doc (#28047) * fix undefined array key (#28048) * Add region and departament for Cuba (#28046) * Update llx_10_c_regions.sql Add Cuba Regions (id_country=77) * Update llx_20_c_departements.sql Add Provinces Cuba (id country=77) * Find the typo (#28050) * Find the typo * clean code * add last_main_doc field to product (#28045) * add las_main_doc field to product * add field fetch * NEW Add Categorie filter for ActionComm (#28041) * New Add Categorie filter for ActionComm New Add Categorie filter for ActionComm * Fix space errors Fix space errors * Fix space errors 2 Fix space errors 2 * Update cunits.class.php (#28056) FIX: error SQL when creating a Cunit * Update codespell-lines-ignore.txt to avoid PR merge conflict --------- Co-authored-by: Laurent Destailleur <eldy@destailleur.fr> Co-authored-by: Frédéric FRANCE <frederic34@users.noreply.github.com> Co-authored-by: thibdrev <thibault.drevet@gmail.com> Co-authored-by: sonikf <93765174+sonikf@users.noreply.github.com> Co-authored-by: Ikarus <44511582+LeKarSol@users.noreply.github.com> Co-authored-by: Anthony Damhet <73399671+EchoLoGeek@users.noreply.github.com> Co-authored-by: Quentin-Seekness <72733832+Quentin-Seekness@users.noreply.github.com>
2024-02-09 15:58:49 +01:00
public static $user = null;
2015-05-12 16:42:35 +02:00
2020-09-19 23:30:29 +02:00
/**
* Constructor
*/
public function __construct()
{
global $db;
$this->db = $db;
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName
/**
* Check access
2015-05-12 16:42:35 +02:00
*
2015-06-02 15:12:19 +02:00
* @return bool
2020-04-03 03:04:23 +02:00
*
* @throws RestException 401 Forbidden
* @throws RestException 503 Technical error
*/
public function __isAllowed()
2015-06-02 15:12:19 +02:00
{
// phpcs:enable
global $conf, $user;
2016-05-08 12:32:18 +02:00
$login = '';
$stored_key = '';
2015-05-12 16:42:35 +02:00
2015-05-02 18:14:51 +02:00
$userClass = Defaults::$userIdentifierClass;
2015-05-12 16:42:35 +02:00
/*foreach ($_SERVER as $key => $val)
{
2021-02-23 17:44:43 +01:00
dol_syslog($key.' - '.$val);
}*/
2017-06-25 12:26:16 +02:00
// api key can be provided in url with parameter api_key=xxx or ni header with header DOLAPIKEY:xxx
$api_key = '';
2024-03-28 17:10:22 +01:00
if (isset($_GET['api_key'])) { // For backward compatibility. Keep $_GET here.
// TODO Add option to disable use of api key on url. Return errors if used.
$api_key = $_GET['api_key'];
}
2021-02-23 17:44:43 +01:00
if (isset($_GET['DOLAPIKEY'])) {
// TODO Add option to disable use of api key on url. Return errors if used.
$api_key = $_GET['DOLAPIKEY']; // With GET method
}
// TODO Can filter on user agent.
//$api_useragent = $_SERVER['HTTP_USER_AGENT'];
if (isset($_SERVER['HTTP_DOLAPIKEY'])) { // HTTP Header entry "DOLAPIKEY: ..." can be read with $_SERVER["HTTP_DOLAPIKEY"]
$api_key = $_SERVER['HTTP_DOLAPIKEY']; // With header method (recommended)
2025-02-17 18:18:57 +01:00
} elseif (empty($api_key)) {
$headers = getallheaders(); // HTTP Header entry "Authorization: Bearer ..." can be read with getallheaders
$api_key = preg_replace('/^Bearer\s+/i', '', empty($headers['Authorization']) ? '' : $headers['Authorization']);
};
2024-02-01 00:54:03 +01:00
$api_key = dol_string_nounprintableascii($api_key);
if (preg_match('/^dolcrypt:/i', $api_key)) {
throw new RestException(503, 'Bad value for the API key. An API key should not start with dolcrypt:');
}
2017-06-25 12:26:16 +02:00
2021-02-23 17:44:43 +01:00
if ($api_key) {
$userentity = 0;
2023-07-19 04:14:49 +02:00
$sql = "SELECT u.login, u.datec, u.api_key,";
$sql .= " u.tms as date_modification, u.entity";
$sql .= " FROM ".MAIN_DB_PREFIX."user as u";
2023-03-13 12:48:25 +01:00
$sql .= " WHERE u.api_key = '".$this->db->escape($api_key)."' OR u.api_key = '".$this->db->escape(dolEncrypt($api_key, '', '', 'dolibarr'))."'";
2020-09-19 23:30:29 +02:00
$result = $this->db->query($sql);
2021-02-23 17:44:43 +01:00
if ($result) {
2023-03-13 12:48:25 +01:00
$nbrows = $this->db->num_rows($result);
if ($nbrows == 1) {
2020-09-19 23:30:29 +02:00
$obj = $this->db->fetch_object($result);
$login = $obj->login;
2023-03-13 12:48:25 +01:00
$stored_key = dolDecrypt($obj->api_key);
$userentity = $obj->entity;
2021-02-23 17:44:43 +01:00
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
$conf->entity = ($obj->entity ? $obj->entity : 1);
// We must also reload global conf to get params from the entity
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);
2020-09-19 23:30:29 +02:00
$conf->setValues($this->db);
}
2023-03-13 12:48:25 +01:00
} elseif ($nbrows > 1) {
throw new RestException(503, 'Error when fetching user api_key : More than 1 user with this apikey');
}
2020-05-21 15:05:19 +02:00
} else {
2020-09-19 23:30:29 +02:00
throw new RestException(503, 'Error when fetching user api_key :'.$this->db->error_msg);
}
2023-07-19 04:14:49 +02:00
if ($login && $stored_key != $api_key) { // This should not happen since we did a search on api_key
$userClass::setCacheIdentifier($api_key);
2015-05-02 18:14:51 +02:00
return false;
}
2015-05-12 16:42:35 +02:00
2023-07-19 04:14:49 +02:00
$genericmessageerroruser = 'Error user not valid (not found with api key or bad status or bad validity dates) (conf->entity='.$conf->entity.')';
2021-02-23 17:44:43 +01:00
if (!$login) {
2023-07-19 04:14:49 +02:00
dol_syslog("functions_isallowed::check_user_api_key Authentication KO for api key: Error when searching login user from api key", LOG_NOTICE);
sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
2023-07-19 04:14:49 +02:00
throw new RestException(401, $genericmessageerroruser);
2016-05-08 12:32:18 +02:00
}
2023-01-18 19:54:38 +01:00
2020-09-19 23:30:29 +02:00
$fuser = new User($this->db);
2024-07-31 18:54:52 +02:00
$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)
if ($result <= 0) {
2023-07-19 04:14:49 +02:00
dol_syslog("functions_isallowed::check_user_api_key Authentication KO for '".$login."': Failed to fetch on entity", LOG_NOTICE);
sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
2023-07-19 04:14:49 +02:00
throw new RestException(401, $genericmessageerroruser);
}
2023-01-27 14:27:51 +01:00
// Check if user status is enabled
if ($fuser->statut != $fuser::STATUS_ENABLED) {
// Status is disabled
2023-07-19 04:14:49 +02:00
dol_syslog("functions_isallowed::check_user_api_key Authentication KO for '".$login."': The user has been disabled", LOG_NOTICE);
sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
2023-07-19 04:14:49 +02:00
throw new RestException(401, $genericmessageerroruser);
2023-01-18 10:48:18 +01:00
}
2021-09-02 16:06:19 +02:00
2023-01-27 14:06:31 +01:00
// Check if session was unvalidated by a password change
if (($fuser->flagdelsessionsbefore && !empty($_SESSION["dol_logindate"]) && $fuser->flagdelsessionsbefore > $_SESSION["dol_logindate"])) {
// Session is no more valid
2023-07-19 04:14:49 +02:00
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.");
sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
2023-07-19 04:14:49 +02:00
throw new RestException(401, $genericmessageerroruser);
2023-01-18 19:54:38 +01:00
}
2023-01-27 14:06:31 +01:00
// Check date validity
if ($fuser->isNotIntoValidityDateRange()) {
// User validity dates are no more valid
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());
sleep(1); // Anti brute force protection. Must be same delay when user and password are not valid.
2023-07-19 04:14:49 +02:00
throw new RestException(401, $genericmessageerroruser);
2023-01-18 19:54:38 +01:00
}
// User seems valid
$fuser->loadRights();
2021-09-02 16:06:19 +02:00
// Set the property $user to the $user of API
static::$user = $fuser;
2015-05-12 16:42:35 +02:00
2021-09-02 16:06:19 +02:00
// Set also the global variable $user to the $user of API
$user = $fuser;
2015-05-12 16:42:35 +02:00
2019-11-04 20:20:38 +01:00
if ($fuser->socid) {
static::$role = 'external';
}
2015-05-12 16:42:35 +02:00
2019-11-04 20:20:38 +01:00
if ($fuser->admin) {
static::$role = 'admin';
}
} else {
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).");
2015-05-02 18:14:51 +02:00
}
$userClass::setCacheIdentifier(static::$role);
Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess';
$requirefortest = static::$requires;
2021-02-23 17:44:43 +01:00
if (!is_array($requirefortest)) {
$requirefortest = explode(',', $requirefortest);
}
return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin';
2015-05-02 18:14:51 +02:00
}
2015-05-12 16:42:35 +02:00
// phpcs:disable PEAR.NamingConventions.ValidFunctionName
2015-06-02 15:12:19 +02:00
/**
* @return string string to be used with WWW-Authenticate header
*/
public function __getWWWAuthenticateString()
{
// phpcs:enable
return '';
}
/**
* Verify access
*
* @param array $m Properties of method
*
* @access private
* @return bool
*/
public static function verifyAccess(array $m)
{
$requires = isset($m['class']['DolibarrApiAccess']['properties']['requires'])
? $m['class']['DolibarrApiAccess']['properties']['requires']
: false;
return $requires
? static::$role == 'admin' || in_array(static::$role, (array) $requires)
: true;
}
2015-05-02 18:14:51 +02:00
}