-
Notifications
You must be signed in to change notification settings - Fork 0
/
Keychain.js
90 lines (85 loc) · 2.85 KB
/
Keychain.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
85
86
87
88
89
90
const identity = require(`ti.identity`);
const KeychainItemNotFoundError = require(`./KeychainItemNotFound`);
const teamId = Ti.App.Properties.getString(`team-id`, Alloy.CFG[`team-id`] || `TEAMID`);
export default class Keychain {
constructor(identifier) {
this.identifier = identifier;
this.keychainItem = identity.createKeychainItem({
identifier,
accessGroup: `${teamId}.${Ti.App.id}`,
});
}
load() {
// eslint-disable-next-line promise/avoid-new
return new Promise((resolve, reject) => {
this.keychainItem.fetchExistence(e => {
console.debug(`keychainItem.exists: ${JSON.stringify(e, null, 2)}`);
if (e.exists) {
const { keychainItem } = this;
this.keychainItem.addEventListener(`read`, function onRead(e) {
// console.debug(`keychainItem.read: ${JSON.stringify(e, null, 2)}`);
keychainItem.removeEventListener(`read`, onRead);
if (!e.success) {
return reject(new Error(`Error reading keychainItem`));
}
// Return the value
return resolve(e.value);
});
this.keychainItem.read();
} else {
reject(new KeychainItemNotFoundError(`Keychain does not exist.`));
}
});
});
}
save(value) {
// eslint-disable-next-line promise/avoid-new
return new Promise((resolve, reject) => {
this.keychainItem.fetchExistence(e => {
console.debug(`keychainItem.exists: ${JSON.stringify(e, null, 2)}`);
const { keychainItem } = this;
if (e.exists) {
this.keychainItem.addEventListener(`update`, function onUpdate(e) {
// console.debug(`keychainItem.update: ${JSON.stringify(e, null, 2)}`);
keychainItem.removeEventListener(`update`, onUpdate);
if (!e.success) {
return reject(new Error(`Error updating keychainItem`));
}
// Return the value
return resolve(e.value);
});
this.keychainItem.update(value);
} else {
this.keychainItem.addEventListener(`save`, function onSave(e) {
// console.debug(`keychainItem.save: ${JSON.stringify(e, null, 2)}`);
keychainItem.removeEventListener(`save`, onSave);
if (!e.success) {
return reject(new Error(`Error saving keychainItem`));
}
// Return the value
return resolve(e.value);
});
this.keychainItem.save(value);
}
});
});
}
reset() {
// eslint-disable-next-line promise/avoid-new
return new Promise((resolve, reject) => {
const { keychainItem } = this;
this.keychainItem.addEventListener(`reset`, function onReset(e) {
// console.debug(`keychainItem.reset: ${JSON.stringify(e, null, 2)}`);
keychainItem.removeEventListener(`reset`, onReset);
if (!e.success) {
return reject(new Error(`Error resetting keychainItem`));
}
// Resolve promise
return resolve();
});
this.keychainItem.reset();
});
}
}
Keychain.KeychainItemNotFoundError = KeychainItemNotFoundError;
module.exports = Keychain;