-
Notifications
You must be signed in to change notification settings - Fork 0
/
mypwd.js
84 lines (65 loc) · 2.08 KB
/
mypwd.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const fs = require('fs');
const os = require('os');
const child_process = require('child_process');
let filename = 'mypwd.json';
const loginKey = 'login';
const passwordKey = 'password';
const pwdTemplate = {
'postgres': {
'login': 'john',
'password': 'myPa$$w0rd',
'note': 'Valid until end of month'
},
'mongo': {
'login': 'admin',
'password': 'myPa$$w0rd2'
}
};
function MyPwdException(message) {
this.message = message;
this.name = 'MyPwdException';
}
function setFilename(f) {
filename = f;
}
function getValues(entry, keys) {
const p = os.homedir + '/' + filename;
let result = [];
let d = getEntryFromDict(entry)
if (d == undefined) {
throw new MyPwdException('Entry "' + entry + '" is missing in "' + p + '".');
}
keys.forEach(e => {
if (d[e] == undefined) {
throw new MyPwdException('Key "' + e + '" is missing in "' + entry + '" entry.');
}
result.push(d[e])
});
return result;
}
function getLogin(entry) {
return getValues(entry, [loginKey])[0];
}
function getPassword(entry) {
return getValues(entry, [passwordKey])[0];
}
function getEntryFromDict(entry) {
const p = os.homedir + '/' + filename;
if (fs.existsSync(p)) {
const cred = JSON.parse(fs.readFileSync(p, 'utf-8'));
return cred[entry];
}
const gpg = p + '.gpg';
if (fs.existsSync(gpg)) {
const stdout = child_process.execSync('gpg --decrypt ' + gpg, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] });
const cred = JSON.parse(stdout);
return cred[entry];
}
fs.writeFileSync(p, JSON.stringify(pwdTemplate, null, 2))
const cred = JSON.parse(fs.readFileSync(p, 'utf-8'));
return cred[entry];
}
module.exports.setFilename = setFilename;
module.exports.getValues = getValues;
module.exports.getLogin = getLogin;
module.exports.getPassword = getPassword;