Call login() once.

This commit is contained in:
Alexander Zobnin
2016-01-31 13:40:24 +03:00
parent 625096cba8
commit 1d3e2337a2

View File

@@ -26,6 +26,8 @@ function (angular, _) {
basicAuth: basicAuth, basicAuth: basicAuth,
withCredentials: withCredentials withCredentials: withCredentials
}; };
this.loginPromise = null;
} }
var p = ZabbixAPI.prototype; var p = ZabbixAPI.prototype;
@@ -45,24 +47,45 @@ function (angular, _) {
// Handle errors // Handle errors
function(error) { function(error) {
if (error.message === "Session terminated, re-login, please.") { if (error.message === "Session terminated, re-login, please.") {
return ZabbixAPIService.login(self.url, self.username, self.password, self.requestOptions) throw 'expired';
.then(function(auth) { return self.login().then(function(auth) {
self.auth = auth; self.auth = auth;
return ZabbixAPIService.request(self.url, method, params, self.requestOptions, self.auth); return ZabbixAPIService.request(self.url, method, params, self.requestOptions, self.auth);
}); });
} }
}); });
} else { } else {
// Login first // Login first
return ZabbixAPIService.login(this.url, this.username, this.password, this.requestOptions) //throw 'unauthenticated';
.then(function(auth) { return self.loginOnce().then(function(auth) {
self.auth = auth; self.auth = auth;
return ZabbixAPIService.request(self.url, method, params, self.requestOptions, self.auth); return ZabbixAPIService.request(self.url, method, params, self.requestOptions, self.auth);
}); });
} }
}; };
/**
* When API unauthenticated or auth token expired each request produce login()
* call. But auth token is common to all requests. This function wraps login() method
* and call it once. If login() already called just wait for it (return its promise).
* @return login promise
*/
p.loginOnce = function() {
var self = this;
var deferred = $q.defer();
if (!self.loginPromise) {
self.loginPromise = deferred.promise;
self.login().then(function(auth) {
self.loginPromise = null;
deferred.resolve(auth);
});
} else {
return self.loginPromise;
}
return deferred.promise;
};
/** /**
* Get authentication token. * Get authentication token.
*/ */