dolibarr  13.0.2
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 
38 
43 class DolibarrApiAccess implements iAuthenticate
44 {
45  const REALM = 'Restricted Dolibarr API';
46 
50  public static $requires = array('user', 'external', 'admin');
51 
55  public static $role = 'user';
56 
60  public static $user = '';
61 
62 
66  public function __construct()
67  {
68  global $db;
69  $this->db = $db;
70  }
71 
72  // phpcs:disable PEAR.NamingConventions.ValidFunctionName
81  public function __isAllowed()
82  {
83  // phpcs:enable
84  global $conf, $db;
85 
86  $login = '';
87  $stored_key = '';
88 
89  $userClass = Defaults::$userIdentifierClass;
90 
91  /*foreach ($_SERVER as $key => $val)
92  {
93  dol_syslog($key.' - '.$val);
94  }*/
95 
96  // api key can be provided in url with parameter api_key=xxx or ni header with header DOLAPIKEY:xxx
97  $api_key = '';
98  if (isset($_GET['api_key'])) // For backward compatibility
99  {
100  // TODO Add option to disable use of api key on url. Return errors if used.
101  $api_key = $_GET['api_key'];
102  }
103  if (isset($_GET['DOLAPIKEY']))
104  {
105  // TODO Add option to disable use of api key on url. Return errors if used.
106  $api_key = $_GET['DOLAPIKEY']; // With GET method
107  }
108  if (isset($_SERVER['HTTP_DOLAPIKEY'])) // Param DOLAPIKEY in header can be read with HTTP_DOLAPIKEY
109  {
110  $api_key = $_SERVER['HTTP_DOLAPIKEY']; // With header method (recommanded)
111  }
112 
113  if ($api_key)
114  {
115  $userentity = 0;
116 
117  $sql = "SELECT u.login, u.datec, u.api_key, ";
118  $sql .= " u.tms as date_modification, u.entity";
119  $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
120  $sql .= " WHERE u.api_key = '".$this->db->escape($api_key)."'";
121  // TODO Check if 2 users has same API key.
122 
123  $result = $this->db->query($sql);
124  if ($result)
125  {
126  if ($this->db->num_rows($result))
127  {
128  $obj = $this->db->fetch_object($result);
129  $login = $obj->login;
130  $stored_key = $obj->api_key;
131  $userentity = $obj->entity;
132 
133  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
134  {
135  $conf->entity = ($obj->entity ? $obj->entity : 1);
136  // We must also reload global conf to get params from the entity
137  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);
138  $conf->setValues($this->db);
139  }
140  }
141  } else {
142  throw new RestException(503, 'Error when fetching user api_key :'.$this->db->error_msg);
143  }
144 
145  if ($stored_key != $api_key) { // This should not happen since we did a search on api_key
146  $userClass::setCacheIdentifier($api_key);
147  return false;
148  }
149 
150  if (!$login)
151  {
152  throw new RestException(503, 'Error when searching login user from api key');
153  }
154  $fuser = new User($this->db);
155  $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)
156  if ($result <= 0) {
157  throw new RestException(503, 'Error when fetching user :'.$fuser->error.' (conf->entity='.$conf->entity.')');
158  }
159  $fuser->getrights();
160  static::$user = $fuser;
161 
162  if ($fuser->socid) {
163  static::$role = 'external';
164  }
165 
166  if ($fuser->admin) {
167  static::$role = 'admin';
168  }
169  } else {
170  throw new RestException(401, "Failed to login to API. No parameter 'HTTP_DOLAPIKEY' on HTTP header (and no parameter DOLAPIKEY in URL).");
171  }
172 
173  $userClass::setCacheIdentifier(static::$role);
174  Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess';
175  $requirefortest = static::$requires;
176  if (!is_array($requirefortest)) $requirefortest = explode(',', $requirefortest);
177  return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin';
178  }
179 
180  // phpcs:disable PEAR.NamingConventions.ValidFunctionName
184  public function __getWWWAuthenticateString()
185  {
186  // phpcs:enable
187  return '';
188  }
189 
198  public static function verifyAccess(array $m)
199  {
200  $requires = isset($m['class']['DolibarrApiAccess']['properties']['requires'])
201  ? $m['class']['DolibarrApiAccess']['properties']['requires']
202  : false;
203 
204 
205  return $requires
206  ? static::$role == 'admin' || in_array(static::$role, (array) $requires)
207  : true;
208  }
209 }
static verifyAccess(array $m)
Verify access.
__construct()
Constructor.
Class to manage Dolibarr users.
Definition: user.class.php:44
$conf db
API class for accounts.
Definition: inc.php:54
__isAllowed()
Check access.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
Dolibarr API access class.
print $_SERVER["PHP_SELF"]
Edit parameters.