Token Caching now works

This commit is contained in:
Amish Shah
2015-12-14 18:06:03 +00:00
parent a122f0994e
commit 8f5722d242
7 changed files with 71 additions and 26 deletions

View File

@@ -265,15 +265,29 @@ export default class InternalClient {
login(email, password) {
var client = this.client;
console.log(this.tokenCacher.done);
if(!this.tokenCacher.done){
return new Promise((resolve, reject) => {
setTimeout(() => {
this.login(email, password).then(resolve).catch(reject);
}, 20);
});
}else{
console.log("Cached - " + this.tokenCacher.getToken(email, password));
} else {
var tk = this.tokenCacher.getToken(email, password);
if( tk ){
return new Promise((resolve, reject) => {
this.client.emit("debug", "bypassed direct API login, used cached token");
this.state = ConnectionState.LOGGED_IN;
this.token = tk;
this.email = email;
this.password = password;
return this.getGateway()
.then(url => {
this.createWS(url);
return tk;
});
});
}
}
if(this.state !== ConnectionState.DISCONNECTED && this.state !== ConnectionState.IDLE) {
@@ -287,6 +301,7 @@ export default class InternalClient {
password
})
.then(res => {
this.client.emit("debug", "direct API login, cached token was unavailable");
var token = res.token;
this.tokenCacher.setToken(email, password, token);
this.state = ConnectionState.LOGGED_IN;

View File

@@ -14,10 +14,11 @@ export default class Cache extends Array {
if (key === this[discrimS])
return this[discrimCacheS][value] || null;
var l = this.length;
for (var i = 0; i < l; i++)
if (this[i][key] == value)
return this[i];
for(var item of this){
if(item[key] == value){
return item;
}
}
return null;
}

View File

@@ -25,10 +25,9 @@ export default class TokenCacher extends EventEmitter {
setToken(email, password, token) {
console.log("wanting to cache", token);
token = new Buffer(token).toString("base64");
var cipher = crypto.createCipher(algo,password)
var crypted = cipher.update(token,'utf8','base64')
crypted += cipher.final('base64');
var cipher = crypto.createCipher(algo, password)
var crypted = cipher.update("valid" + token, 'utf8', 'hex')
crypted += cipher.final('hex');
this.data[email] = crypted;
this.save();
}
@@ -37,16 +36,17 @@ export default class TokenCacher extends EventEmitter {
fs.writeJson(this.savePath, this.data);
}
getToken(email, password){
getToken(email, password) {
if (this.data[email]) {
try {
var decipher = crypto.createDecipher(algo, password)
var dec = decipher.update(this.data[email], "base64", 'utf8')
var dec = decipher.update(this.data[email], "hex", 'utf8');
dec += decipher.final('utf8');
return new Buffer(dec, "base64").toString("ascii");
return (dec.indexOf("valid") === 0 ? dec.substr(5) : false);
} catch (e) {
// not a valid token
return null;
}