dolibarr 23.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 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21use Luracast\Restler\RestException;
22
23require_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
24require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
25
29class Login
30{
34 public $db;
35
39 public function __construct()
40 {
41 global $db;
42 $this->db = $db;
43
44 //$conf->global->API_DISABLE_LOGIN_API = 1;
45 if (getDolGlobalString('API_DISABLE_LOGIN_API')) {
46 throw new RestException(403, "Error login APIs are disabled. You must get the token from backoffice to be able to use APIs");
47 }
48 }
49
71 public function loginUnsecured($login, $password, $entity = '', $reset = 0)
72 {
73 return $this->index($login, $password, $entity, $reset);
74 }
75
97 public function index($login, $password, $entity = '', $reset = 0)
98 {
99 global $dolibarr_main_authentication, $dolibarr_auto_user;
100
101 // Is the login API disabled ? The token must be generated from backoffice only.
102 if (getDolGlobalString('API_DISABLE_LOGIN_API')) {
103 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);
104 throw new RestException(403, "Error, the login API has been disabled for security purpose. You must generate or get the token from the backoffice.");
105 }
106
107 // Authentication mode
108 if (empty($dolibarr_main_authentication) || $dolibarr_main_authentication == 'openid_connect') {
109 $dolibarr_main_authentication = 'dolibarr';
110 }
111
112 // Authentication mode: forceuser
113 if ($dolibarr_main_authentication == 'forceuser') {
114 if (empty($dolibarr_auto_user)) {
115 $dolibarr_auto_user = 'auto';
116 }
117 if ($dolibarr_auto_user != $login) {
118 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.");
119 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.");
120 }
121 }
122
123 // Set authmode
124 $authmode = explode(',', $dolibarr_main_authentication);
125
126 if ($entity != '' && !is_numeric($entity)) {
127 throw new RestException(403, "Bad value for entity, must be the numeric ID of company.");
128 }
129 if ($entity == '') {
130 $entity = 1;
131 }
132
133 include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
134 $login = checkLoginPassEntity($login, $password, $entity, $authmode, 'api'); // Check credentials.
135 if ($login === '--bad-login-validity--') {
136 $login = '';
137 }
138 if (empty($login)) {
139 throw new RestException(403, 'Access denied');
140 }
141
142 $token = 'failedtogenerateorgettoken';
143
144 $tmpuser = new User($this->db);
145 $tmpuser->fetch(0, $login, '0', 0, $entity);
146 if (empty($tmpuser->id)) {
147 throw new RestException(500, 'Failed to load user');
148 }
149
150 // Renew the hash
151 if (empty($tmpuser->api_key) || $reset) {
152 $tmpuser->loadRights();
153 if (!$tmpuser->hasRight('user', 'self', 'creer')) {
154 if (empty($tmpuser->api_key)) {
155 throw new RestException(403, 'No API token set for this user and user need write permission on itself to reset its API token');
156 } else {
157 throw new RestException(403, 'User need write permission on itself to reset its API token');
158 }
159 }
160
161 // Generate token for user
162 $token = dol_hash($login.uniqid().getDolGlobalString('MAIN_API_KEY'), '1');
163
164 // We store API token into database
165 $sql = "UPDATE ".MAIN_DB_PREFIX."user";
166 $sql .= " SET api_key = '".$this->db->escape(dolEncrypt($token, '', '', 'dolibarr'))."'";
167 $sql .= " WHERE login = '".$this->db->escape($login)."'";
168
169 dol_syslog(get_class($this)."::login", LOG_DEBUG); // No log
170 $result = $this->db->query($sql);
171 if (!$result) {
172 throw new RestException(500, 'Error when updating api_key for user :'.$this->db->lasterror());
173 }
174 } else {
175 $token = $tmpuser->api_key;
176 if (!utf8_check($token)) {
177 throw new RestException(500, 'Error, the API token of this user has a non valid value. Try to update it with a valid value.');
178 }
179 }
180
181 if (!ascii_check($token)) {
182 throw new RestException(500, 'Error the token for this user has not an hexa format. Try first to reset it.');
183 }
184
185 //return token
186 return array(
187 'success' => array(
188 'code' => 200,
189 'token' => $token,
190 'entity' => $tmpuser->entity,
191 '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.')
192 )
193 );
194 }
195}
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 a 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 successful.
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.
dolEncrypt($chain, $key='', $ciphering='', $forceseed='')
Encode a string with a symmetric encryption.