dolibarr  x.y.z
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  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <https://www.gnu.org/licenses/>.
17  */
18 
19 // Create the autoloader for Luracast
20 require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/AutoLoader.php';
21 call_user_func(function () {
22  $loader = Luracast\Restler\AutoLoader::instance();
23  spl_autoload_register($loader);
24  return $loader;
25 });
26 
27 require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/iAuthenticate.php';
28 require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/iUseAuthentication.php';
29 require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Resources.php';
30 require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Defaults.php';
31 require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/RestException.php';
32 use \Luracast\Restler\iAuthenticate;
33 use \Luracast\Restler\iUseAuthentication;
34 use \Luracast\Restler\Resources;
35 use \Luracast\Restler\Defaults;
36 use \Luracast\Restler\RestException;
37 
42 class DolibarrApiAccess implements iAuthenticate
43 {
44  const REALM = 'Restricted Dolibarr API';
45 
49  public static $requires = array('user', 'external', 'admin');
50 
54  public static $role = 'user';
55 
59  public static $user = '';
60 
61 
65  public function __construct()
66  {
67  global $db;
68  $this->db = $db;
69  }
70 
71  // phpcs:disable PEAR.NamingConventions.ValidFunctionName
80  public function __isAllowed()
81  {
82  // phpcs:enable
83  global $conf, $db, $user;
84 
85  $login = '';
86  $stored_key = '';
87 
88  $userClass = Defaults::$userIdentifierClass;
89 
90  /*foreach ($_SERVER as $key => $val)
91  {
92  dol_syslog($key.' - '.$val);
93  }*/
94 
95  // api key can be provided in url with parameter api_key=xxx or ni header with header DOLAPIKEY:xxx
96  $api_key = '';
97  if (isset($_GET['api_key'])) { // For backward compatibility
98  // TODO Add option to disable use of api key on url. Return errors if used.
99  $api_key = $_GET['api_key'];
100  }
101  if (isset($_GET['DOLAPIKEY'])) {
102  // TODO Add option to disable use of api key on url. Return errors if used.
103  $api_key = $_GET['DOLAPIKEY']; // With GET method
104  }
105  if (isset($_SERVER['HTTP_DOLAPIKEY'])) { // Param DOLAPIKEY in header can be read with HTTP_DOLAPIKEY
106  $api_key = $_SERVER['HTTP_DOLAPIKEY']; // With header method (recommanded)
107  }
108 
109  if ($api_key) {
110  $userentity = 0;
111 
112  $sql = "SELECT u.login, u.datec, u.api_key, ";
113  $sql .= " u.tms as date_modification, u.entity";
114  $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
115  $sql .= " WHERE u.api_key = '".$this->db->escape($api_key)."'";
116  // TODO Check if 2 users has same API key.
117 
118  $result = $this->db->query($sql);
119  if ($result) {
120  if ($this->db->num_rows($result)) {
121  $obj = $this->db->fetch_object($result);
122  $login = $obj->login;
123  $stored_key = $obj->api_key;
124  $userentity = $obj->entity;
125 
126  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
127  $conf->entity = ($obj->entity ? $obj->entity : 1);
128  // We must also reload global conf to get params from the entity
129  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);
130  $conf->setValues($this->db);
131  }
132  }
133  } else {
134  throw new RestException(503, 'Error when fetching user api_key :'.$this->db->error_msg);
135  }
136 
137  if ($stored_key != $api_key) { // This should not happen since we did a search on api_key
138  $userClass::setCacheIdentifier($api_key);
139  return false;
140  }
141 
142  if (!$login) {
143  throw new RestException(503, 'Error when searching login user from api key');
144  }
145  $fuser = new User($this->db);
146  $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)
147  if ($result <= 0) {
148  throw new RestException(503, 'Error when fetching user :'.$fuser->error.' (conf->entity='.$conf->entity.')');
149  }
150 
151  $fuser->getrights();
152 
153  // Set the property $user to the $user of API
154  static::$user = $fuser;
155 
156  // Set also the global variable $user to the $user of API
157  $user = $fuser;
158 
159  if ($fuser->socid) {
160  static::$role = 'external';
161  }
162 
163  if ($fuser->admin) {
164  static::$role = 'admin';
165  }
166  } else {
167  throw new RestException(401, "Failed to login to API. No parameter 'HTTP_DOLAPIKEY' on HTTP header (and no parameter DOLAPIKEY in URL).");
168  }
169 
170  $userClass::setCacheIdentifier(static::$role);
171  Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess';
172  $requirefortest = static::$requires;
173  if (!is_array($requirefortest)) {
174  $requirefortest = explode(',', $requirefortest);
175  }
176  return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin';
177  }
178 
179  // phpcs:disable PEAR.NamingConventions.ValidFunctionName
183  public function __getWWWAuthenticateString()
184  {
185  // phpcs:enable
186  return '';
187  }
188 
197  public static function verifyAccess(array $m)
198  {
199  $requires = isset($m['class']['DolibarrApiAccess']['properties']['requires'])
200  ? $m['class']['DolibarrApiAccess']['properties']['requires']
201  : false;
202 
203 
204  return $requires
205  ? static::$role == 'admin' || in_array(static::$role, (array) $requires)
206  : true;
207  }
208 }
Dolibarr API access class.
__construct()
Constructor.
__isAllowed()
Check access.
static verifyAccess(array $m)
Verify access.
Class to manage Dolibarr users.
Definition: user.class.php:45
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
$conf db
API class for accounts.
Definition: inc.php:41