dolibarr  18.0.6
api_login.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 use Luracast\Restler\RestException;
20 
21 require_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
22 require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
23 
27 class Login
28 {
29 
33  public function __construct()
34  {
35  global $conf, $db;
36  $this->db = $db;
37 
38  //$conf->global->MAIN_MODULE_API_LOGIN_DISABLED = 1;
39  if (!empty($conf->global->MAIN_MODULE_API_LOGIN_DISABLED)) {
40  throw new RestException(403, "Error login APIs are disabled. You must get the token from backoffice to be able to use APIs");
41  }
42  }
43 
63  public function loginUnsecured($login, $password, $entity = '', $reset = 0)
64  {
65  return $this->index($login, $password, $entity, $reset);
66  }
67 
87  public function index($login, $password, $entity = '', $reset = 0)
88  {
89  global $conf, $dolibarr_main_authentication, $dolibarr_auto_user;
90 
91  // Is the login API disabled ? The token must be generated from backoffice only.
92  if (!empty($conf->global->API_DISABLE_LOGIN_API)) {
93  dol_syslog("Warning: A try to use the login API has been done while the login API is disabled. You must generate or get the token from the backoffice.", LOG_WARNING);
94  throw new RestException(403, "Error, the login API has been disabled for security purpose. You must generate or get the token from the backoffice.");
95  }
96 
97  // Authentication mode
98  if (empty($dolibarr_main_authentication)) {
99  $dolibarr_main_authentication = 'dolibarr';
100  }
101 
102  // Authentication mode: forceuser
103  if ($dolibarr_main_authentication == 'forceuser') {
104  if (empty($dolibarr_auto_user)) {
105  $dolibarr_auto_user = 'auto';
106  }
107  if ($dolibarr_auto_user != $login) {
108  dol_syslog("Warning: your instance is set to use the automatic forced login '".$dolibarr_auto_user."' that is not the requested login. API usage is forbidden in this mode.");
109  throw new RestException(403, "Your instance is set to use the automatic login '".$dolibarr_auto_user."' that is not the requested login. API usage is forbidden in this mode.");
110  }
111  }
112 
113  // Set authmode
114  $authmode = explode(',', $dolibarr_main_authentication);
115 
116  if ($entity != '' && !is_numeric($entity)) {
117  throw new RestException(403, "Bad value for entity, must be the numeric ID of company.");
118  }
119  if ($entity == '') {
120  $entity = 1;
121  }
122 
123  include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
124  $login = checkLoginPassEntity($login, $password, $entity, $authmode, 'api'); // Check credentials.
125  if ($login === '--bad-login-validity--') {
126  $login = '';
127  }
128  if (empty($login)) {
129  throw new RestException(403, 'Access denied');
130  }
131 
132  $token = 'failedtogenerateorgettoken';
133 
134  $tmpuser = new User($this->db);
135  $tmpuser->fetch(0, $login, 0, 0, $entity);
136  if (empty($tmpuser->id)) {
137  throw new RestException(500, 'Failed to load user');
138  }
139 
140  // Renew the hash
141  if (empty($tmpuser->api_key) || $reset) {
142  $tmpuser->getrights();
143  if (empty($tmpuser->rights->user->self->creer)) {
144  if (empty($tmpuser->api_key)) {
145  throw new RestException(403, 'No API token set for this user and user need write permission on itself to reset its API token');
146  } else {
147  throw new RestException(403, 'User need write permission on itself to reset its API token');
148  }
149  }
150 
151  // Generate token for user
152  $token = dol_hash($login.uniqid().(empty($conf->global->MAIN_API_KEY)?'':$conf->global->MAIN_API_KEY), 1);
153 
154  // We store API token into database
155  $sql = "UPDATE ".MAIN_DB_PREFIX."user";
156  $sql .= " SET api_key = '".$this->db->escape(dolEncrypt($token, '', '', 'dolibarr'))."'";
157  $sql .= " WHERE login = '".$this->db->escape($login)."'";
158 
159  dol_syslog(get_class($this)."::login", LOG_DEBUG); // No log
160  $result = $this->db->query($sql);
161  if (!$result) {
162  throw new RestException(500, 'Error when updating api_key for user :'.$this->db->lasterror());
163  }
164  } else {
165  $token = $tmpuser->api_key;
166  }
167 
168  if (!ascii_check($token)) {
169  throw new RestException(500, 'Error the token for this user has not an hexa format. Try first to reset it.');
170  }
171 
172  //return token
173  return array(
174  'success' => array(
175  'code' => 200,
176  'token' => $token,
177  'entity' => $tmpuser->entity,
178  'message' => 'Welcome '.$login.($reset ? ' - Token is new' : ' - This is your token (recorded for your user). You can use it to make any REST API call, or enter it into the DOLAPIKEY field to use the Dolibarr API explorer.')
179  )
180  );
181  }
182 }
API that allows to log in with an user account.
__construct()
Constructor of the class.
index($login, $password, $entity='', $reset=0)
Login.
loginUnsecured($login, $password, $entity='', $reset=0)
Login.
Class to manage Dolibarr users.
Definition: user.class.php:48
if(isModEnabled('facture') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:746
ascii_check($str)
Check if a string is in ASCII.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $authmode, $context='')
Return a login if login/pass was successfull.
dolEncrypt($chain, $key='', $ciphering='AES-256-CTR', $forceseed='')
Encode a string with a symetric encryption.
dol_hash($chain, $type='0')
Returns a hash (non reversible encryption) of a string.