dolibarr 19.0.3
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
19use Luracast\Restler\RestException;
20
21require_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
22require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
23
27class Login
28{
32 public $db;
33
37 public function __construct()
38 {
39 global $conf, $db;
40 $this->db = $db;
41
42 //$conf->global->MAIN_MODULE_API_LOGIN_DISABLED = 1;
43 if (getDolGlobalString('MAIN_MODULE_API_LOGIN_DISABLED')) {
44 throw new RestException(403, "Error login APIs are disabled. You must get the token from backoffice to be able to use APIs");
45 }
46 }
47
67 public function loginUnsecured($login, $password, $entity = '', $reset = 0)
68 {
69 return $this->index($login, $password, $entity, $reset);
70 }
71
91 public function index($login, $password, $entity = '', $reset = 0)
92 {
93 global $conf, $dolibarr_main_authentication, $dolibarr_auto_user;
94
95 // Is the login API disabled ? The token must be generated from backoffice only.
96 if (getDolGlobalString('API_DISABLE_LOGIN_API')) {
97 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);
98 throw new RestException(403, "Error, the login API has been disabled for security purpose. You must generate or get the token from the backoffice.");
99 }
100
101 // Authentication mode
102 if (empty($dolibarr_main_authentication)) {
103 $dolibarr_main_authentication = 'dolibarr';
104 }
105
106 // Authentication mode: forceuser
107 if ($dolibarr_main_authentication == 'forceuser') {
108 if (empty($dolibarr_auto_user)) {
109 $dolibarr_auto_user = 'auto';
110 }
111 if ($dolibarr_auto_user != $login) {
112 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.");
113 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.");
114 }
115 }
116
117 // Set authmode
118 $authmode = explode(',', $dolibarr_main_authentication);
119
120 if ($entity != '' && !is_numeric($entity)) {
121 throw new RestException(403, "Bad value for entity, must be the numeric ID of company.");
122 }
123 if ($entity == '') {
124 $entity = 1;
125 }
126
127 include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
128 $login = checkLoginPassEntity($login, $password, $entity, $authmode, 'api'); // Check credentials.
129 if ($login === '--bad-login-validity--') {
130 $login = '';
131 }
132 if (empty($login)) {
133 throw new RestException(403, 'Access denied');
134 }
135
136 $token = 'failedtogenerateorgettoken';
137
138 $tmpuser = new User($this->db);
139 $tmpuser->fetch(0, $login, 0, 0, $entity);
140 if (empty($tmpuser->id)) {
141 throw new RestException(500, 'Failed to load user');
142 }
143
144 // Renew the hash
145 if (empty($tmpuser->api_key) || $reset) {
146 $tmpuser->getrights();
147 if (!$tmpuser->hasRight('user', 'self', 'creer')) {
148 if (empty($tmpuser->api_key)) {
149 throw new RestException(403, 'No API token set for this user and user need write permission on itself to reset its API token');
150 } else {
151 throw new RestException(403, 'User need write permission on itself to reset its API token');
152 }
153 }
154
155 // Generate token for user
156 $token = dol_hash($login.uniqid().(!getDolGlobalString('MAIN_API_KEY') ? '' : $conf->global->MAIN_API_KEY), 1);
157
158 // We store API token into database
159 $sql = "UPDATE ".MAIN_DB_PREFIX."user";
160 $sql .= " SET api_key = '".$this->db->escape(dolEncrypt($token, '', '', 'dolibarr'))."'";
161 $sql .= " WHERE login = '".$this->db->escape($login)."'";
162
163 dol_syslog(get_class($this)."::login", LOG_DEBUG); // No log
164 $result = $this->db->query($sql);
165 if (!$result) {
166 throw new RestException(500, 'Error when updating api_key for user :'.$this->db->lasterror());
167 }
168 } else {
169 $token = $tmpuser->api_key;
170 if (!utf8_check($token)) {
171 throw new RestException(500, 'Error, the API token of this user has a non valid value. Try to update it with a valid value.');
172 }
173 }
174
175 if (!ascii_check($token)) {
176 throw new RestException(500, 'Error the token for this user has not an hexa format. Try first to reset it.');
177 }
178
179 //return token
180 return array(
181 'success' => array(
182 'code' => 200,
183 'token' => $token,
184 'entity' => $tmpuser->entity,
185 '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.')
186 )
187 );
188 }
189}
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.
ascii_check($str)
Check if a string is in ASCII.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
utf8_check($str)
Check if a string is in UTF8.
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', $nosalt=0)
Returns a hash (non reversible encryption) of a string.