golos-lib-js
Version:
Golos-js the JavaScript library with API for GOLOS blockchain
73 lines (72 loc) • 2.03 kB
JavaScript
"use strict";
var _ecc = require("../ecc");
class MultiSessionData {
constructor(_ref) {
let {
key,
currentName,
accounts
} = _ref;
this.key = key;
this.currentName = currentName;
this.accounts = accounts;
}
getVal(account, field) {
let defaultVal = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
if (this.accounts[account]) return this.accounts[account][field] || defaultVal;
return defaultVal;
}
setVal(account, field, val) {
this.accounts[account] = this.accounts[account] || {};
this.accounts[account][field] = val;
return this;
}
addKey(account, authType, val) {
if (val && val.toWif) val = val.toWif();
try {
_ecc.PrivateKey.fromWif(val);
} catch (e) {
val = _ecc.PrivateKey.fromSeed(account + authType + val).toString();
}
return this.setVal(account, authType, val);
}
addMultiAuth(account) {
return this.setVal(account, 'multiauth', true);
}
setCurrent(account) {
if (!this.accounts[account]) throw new Error('Cannot set current account to: ' + account + ' because it does not saved');
this.currentName = account;
return this;
}
logout(account) {
let newCurrent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
delete this.accounts[account];
if (this.currentName === account) {
this.currentName = '';
if (newCurrent) {
const arr = Object.entries(this.accounts);
if (arr[0]) {
this.currentName = arr[0][0];
newCurrent.name = arr[0][0];
newCurrent.data = arr[0][1];
}
}
}
return this;
}
clear() {
this.accounts = {};
this.currentName = '';
return this;
}
save() {
const json = JSON.stringify({
currentName: this.currentName,
accounts: this.accounts
});
const buf = new Buffer(json).toString('hex');
localStorage.setItem(this.key, buf);
return this;
}
}
module.exports = MultiSessionData;