UNPKG

appcenter-cli

Version:

Command line tool for Visual Studio App Center

88 lines (87 loc) 3 kB
"use strict"; // // file-token-store - implementation of token store that stores the data in // a JSON encoded file on dist. // // This doesn't secure the data in any way, relies on the directory having // proper security settings. // Object.defineProperty(exports, "__esModule", { value: true }); exports.createFileTokenStore = exports.FileTokenStore = void 0; const fs = require("fs"); const path = require("path"); const rx = require("rxjs"); const operators_1 = require("rxjs/operators"); const lodash_1 = require("lodash"); const debug = require("debug")("appcenter-cli:util:token-store:file:file-token-store"); class FileTokenStore { constructor(filePath) { this.filePath = filePath; this.tokenStoreCache = null; } getStoreFilePath() { return this.filePath; } list() { this.loadTokenStoreCache(); return rx .from(lodash_1.toPairs(this.tokenStoreCache)) .pipe(operators_1.map((pair) => ({ key: pair[0], accessToken: pair[1] }))); } get(key) { this.loadTokenStoreCache(); const token = this.tokenStoreCache[key]; if (!token) { return Promise.resolve(null); } return Promise.resolve({ key: key, accessToken: token }); } set(key, value) { this.loadTokenStoreCache(); this.tokenStoreCache[key] = value; this.writeTokenStoreCache(); return Promise.resolve(); } remove(key) { this.loadTokenStoreCache(); delete this.tokenStoreCache[key]; this.writeTokenStoreCache(); return Promise.resolve(); } loadTokenStoreCache() { if (this.tokenStoreCache === null) { debug(`Loading token store cache from file ${this.filePath}`); // Ensure directory exists try { fs.mkdirSync(path.dirname(this.filePath)); } catch (err) { if (err.code !== "EEXIST") { debug(`Unable to create token store cache directory: ${err.message}`); throw err; } } try { this.tokenStoreCache = JSON.parse(fs.readFileSync(this.filePath, "utf8")); debug(`Token store loaded from file`); } catch (err) { if (err.code !== "ENOENT") { debug(`Failed to load or parse token store file`); throw err; } debug(`No token cache file, creating new empty cache`); this.tokenStoreCache = {}; } } } writeTokenStoreCache() { debug(`Saving token store file to ${this.filePath}`); fs.writeFileSync(this.filePath, JSON.stringify(this.tokenStoreCache)); } } exports.FileTokenStore = FileTokenStore; function createFileTokenStore(pathName) { return new FileTokenStore(pathName); } exports.createFileTokenStore = createFileTokenStore;