1 | const fs = require('mz/fs');
|
2 | const { homedir } = require('os');
|
3 | const path = require('path');
|
4 | const yaml = require('js-yaml');
|
5 |
|
6 | const userConfDirectory = process.env.BINARIS_CONF_DIR || process.env.HOME || homedir();
|
7 | const userConfFile = '.binaris.yml';
|
8 | const userConfPath = path.join(userConfDirectory, userConfFile);
|
9 |
|
10 | const loadUserConf = async function loadUserConf() {
|
11 | const confString = await fs.readFile(userConfPath, 'utf8');
|
12 | const userConf = yaml.safeLoad(confString);
|
13 | return userConf;
|
14 | };
|
15 |
|
16 | const saveUserConf = async function saveUserConf(userConf) {
|
17 | const confString = yaml.dump(userConf);
|
18 | await fs.writeFile(userConfPath, confString, 'utf8');
|
19 | };
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 | const updateAPIKey = async function updateAPIKey(apiKey) {
|
29 | let currentConf = {};
|
30 | try {
|
31 | currentConf = await loadUserConf();
|
32 | } catch (err) {}
|
33 | await saveUserConf(Object.assign({}, currentConf, { apiKey }));
|
34 | };
|
35 |
|
36 | const getAPIKey = async function getAPIKey() {
|
37 | const apiKey = process.env.BINARIS_API_KEY;
|
38 | if (apiKey) return apiKey;
|
39 |
|
40 | let userConf;
|
41 | try {
|
42 | userConf = await loadUserConf();
|
43 | } catch (err) {
|
44 | throw new Error('Binaris conf file could not be read and BINARIS_API_KEY is undefined, please use "bn login"');
|
45 | }
|
46 |
|
47 | if (!Object.prototype.hasOwnProperty.call(userConf, 'apiKey')) {
|
48 | throw new Error(
|
49 | `Invalid Binaris conf file (missing API key) ${userConfPath}`);
|
50 | }
|
51 | return userConf.apiKey;
|
52 | };
|
53 |
|
54 | module.exports = {
|
55 | getAPIKey,
|
56 | updateAPIKey,
|
57 | };
|