Commit 1011a015 by tdgiang

Add SobanleClient token cache and login

parent 60aa61c5
"use strict";
var config = require(__config_path + "/config");
var ApiRequest = require("./ApiRequest");
var tokenCache = { token: null, expiresAt: 0 };
function login(callback) {
var url = config.sobanle.base_url + "/login";
ApiRequest.postOtherUrl(url, { login: config.sobanle.username, password: config.sobanle.password }, function (err, body) {
if (err) {
return callback(err);
}
if (!body || !body.access_token) {
return callback(new Error("SOBANLE_LOGIN_FAILED"));
}
tokenCache.token = body.access_token;
var expiresInMs = (body.expires_in || 0) * 1000;
// Refresh a bit early to avoid racing a near-expiry token. Headroom scales
// with the token's own TTL (capped at 60s) rather than a flat 60s, so a
// short-TTL token isn't already "expired" the instant it's cached.
var earlyRefreshMs = Math.min(60000, expiresInMs * 0.1);
tokenCache.expiresAt = Date.now() + expiresInMs - earlyRefreshMs;
callback(null, body.access_token);
});
}
exports.login = login;
function getToken(callback) {
if (tokenCache.token && Date.now() < tokenCache.expiresAt) {
return callback(null, tokenCache.token);
}
exports.login(callback);
}
exports.getToken = getToken;
exports._resetTokenCacheForTest = function () {
tokenCache.token = null;
tokenCache.expiresAt = 0;
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment