-
-
Notifications
You must be signed in to change notification settings - Fork 437
/
Copy pathkeychain.ts
76 lines (68 loc) · 1.58 KB
/
keychain.ts
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
import type * as keytarType from 'keytar';
export type KeychainConfig = {
credentialsSection: string;
account: string;
};
type Keytar = {
getPassword: typeof keytarType['getPassword'];
setPassword: typeof keytarType['setPassword'];
deletePassword: typeof keytarType['deletePassword'];
};
export class Keychain {
credentialsSection: string;
account: string;
constructor(config: KeychainConfig) {
this.credentialsSection = config.credentialsSection;
this.account = config.account;
}
getKeytar(): Keytar | undefined {
try {
return require('keytar');
} catch (err) {
console.log(err);
}
return undefined;
}
async getStoredCredentials(): Promise<string | undefined | null> {
const keytar = this.getKeytar();
if (!keytar) {
return undefined;
}
try {
return keytar.getPassword(this.credentialsSection, this.account);
} catch {
return undefined;
}
}
async storeCredentials(stringifiedToken: string): Promise<boolean> {
const keytar = this.getKeytar();
if (!keytar) {
return false;
}
try {
await keytar.setPassword(
this.credentialsSection,
this.account,
stringifiedToken
);
return true;
} catch {
return false;
}
}
async deleteCredentials(): Promise<boolean> {
const keytar = this.getKeytar();
if (!keytar) {
return false;
}
try {
const result = await keytar.deletePassword(
this.credentialsSection,
this.account
);
return result;
} catch {
return false;
}
}
}