diff --git a/htdocs/api/admin/explorer.php b/htdocs/api/admin/explorer.php
index 1a4f3f7b9a3..913abe72018 100644
--- a/htdocs/api/admin/explorer.php
+++ b/htdocs/api/admin/explorer.php
@@ -156,7 +156,7 @@ $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain
// Show message
print '
';
$message='';
-$url=''.$urlwithroot.'/api/index.php/login?login='.urlencode($user->login).'&password=yourpassword';
+$url=''.$urlwithroot.'/api/index.php/login?login='.urlencode($user->login).'&password=yourpassword[&reset=1]';
$message.=$langs->trans("UrlToGetKeyToUseAPIs").':
';
$message.=img_picto('','object_globe.png').' '.$url;
print $message;
diff --git a/htdocs/api/class/api_generic.class.php b/htdocs/api/class/api_generic.class.php
index b15c489d9c2..038621b6235 100644
--- a/htdocs/api/class/api_generic.class.php
+++ b/htdocs/api/class/api_generic.class.php
@@ -43,11 +43,12 @@ class GenericApi extends DolibarrApi
* @param string $login Username
* @param string $password User password
* @param int $entity User entity
- * @return array Response status and user token
+ * @param int $reset Reset token
+ * @return array Response status and user token
*
* @throws RestException
*/
- public function login($login, $password, $entity = 0) {
+ public function login($login, $password, $entity=0, $reset=0) {
global $conf, $dolibarr_main_authentication, $dolibarr_auto_user;
@@ -67,27 +68,40 @@ class GenericApi extends DolibarrApi
throw new RestException(403, 'Access denied');
}
- // Generate token for user
- $token = dol_hash($login.uniqid().$conf->global->MAIN_API_KEY,1);
-
- // We store API token into database
- $sql = "UPDATE ".MAIN_DB_PREFIX."user";
- $sql.= " SET api_key = '".$this->db->escape($token)."'";
- $sql.= " WHERE login = '".$this->db->escape($login)."'";
-
- dol_syslog(get_class($this)."::login", LOG_DEBUG); // No log
- $result = $this->db->query($sql);
- if (!$result)
+ $token = 'failedtogenerateorgettoken';
+
+ $tmpuser=new User($this->db);
+ $tmpuser->fetch(0, $login);
+
+ // Renew the hash
+ if (empty($tmpuser->api_key) || $reset)
{
- throw new RestException(500, 'Error when updating user :'.$this->db->error_msg);
+ // Generate token for user
+ $token = dol_hash($login.uniqid().$conf->global->MAIN_API_KEY,1);
+
+ // We store API token into database
+ $sql = "UPDATE ".MAIN_DB_PREFIX."user";
+ $sql.= " SET api_key = '".$this->db->escape($token)."'";
+ $sql.= " WHERE login = '".$this->db->escape($login)."'";
+
+ dol_syslog(get_class($this)."::login", LOG_DEBUG); // No log
+ $result = $this->db->query($sql);
+ if (!$result)
+ {
+ throw new RestException(500, 'Error when updating api_key for user :'.$this->db->lasterror());
+ }
}
-
+ else
+ {
+ $token = $tmpuser->api_key;
+ }
+
//return token
return array(
'success' => array(
'code' => 200,
'token' => $token,
- 'message' => 'Welcome ' . $login
+ 'message' => 'Welcome ' . $login.($reset?' - Token is new':' - Token was generated by a previous call')
)
);
}