mirror of
https://gitlab.winehq.org/wine/wine-gecko.git
synced 2024-09-13 09:24:08 -07:00
Bug 971054 - Part 4. Class to manage the service's auth token lifetime and renewal. r=florian
This commit is contained in:
parent
928c476bfc
commit
e7233647cc
@ -247,6 +247,77 @@ BingRequest.prototype = {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Authentication Token manager for the API
|
||||
*/
|
||||
let BingTokenManager = {
|
||||
_currentToken: null,
|
||||
_currentExpiryTime: 0,
|
||||
_pendingRequest: null,
|
||||
|
||||
/**
|
||||
* Get a valid, non-expired token to be used for the API calls.
|
||||
*
|
||||
* @returns {Promise} A promise that resolves with the token
|
||||
* string once it is obtained. The token returned
|
||||
* can be the same one used in the past if it is still
|
||||
* valid.
|
||||
*/
|
||||
getToken: function() {
|
||||
if (this._pendingRequest) {
|
||||
return this._pendingRequest;
|
||||
}
|
||||
|
||||
let remainingMs = this._currentExpiryTime - new Date();
|
||||
// Our existing token is still good for more than a minute, let's use it.
|
||||
if (remainingMs > 60 * 1000) {
|
||||
return Promise.resolve(this._currentToken);
|
||||
}
|
||||
|
||||
return this._getNewToken();
|
||||
},
|
||||
|
||||
/**
|
||||
* Generates a new token from the server.
|
||||
*
|
||||
* @returns {Promise} A promise that resolves with the token
|
||||
* string once it is obtained.
|
||||
*/
|
||||
_getNewToken: function() {
|
||||
let request = new RESTRequest("https://datamarket.accesscontrol.windows.net/v2/OAuth2-13");
|
||||
request.setHeader("Content-type", "application/x-www-form-urlencoded");
|
||||
let params = [
|
||||
"grant_type=client_credentials",
|
||||
"scope=" + encodeURIComponent("http://api.microsofttranslator.com"),
|
||||
"client_id=",
|
||||
"client_secret="
|
||||
];
|
||||
|
||||
let deferred = Promise.defer();
|
||||
this._pendingRequest = deferred.promise;
|
||||
request.post(params.join("&"), function(err) {
|
||||
this._pendingRequest = null;
|
||||
|
||||
if (err) {
|
||||
deferred.reject(err);
|
||||
}
|
||||
|
||||
try {
|
||||
let json = JSON.parse(this.response.body);
|
||||
let token = json.access_token;
|
||||
let expires_in = json.expires_in;
|
||||
BingTokenManager._currentToken = token;
|
||||
BingTokenManager._currentExpiryTime = new Date(Date.now() + expires_in * 1000);
|
||||
deferred.resolve(token);
|
||||
} catch (e) {
|
||||
deferred.reject(e);
|
||||
}
|
||||
});
|
||||
|
||||
return deferred.promise;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Escape a string to be valid XML content.
|
||||
*/
|
||||
|
Loading…
Reference in New Issue
Block a user