-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
250 lines (224 loc) · 7.72 KB
/
index.js
File metadata and controls
250 lines (224 loc) · 7.72 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
/**
* Requires
*
* @ignore
*/
var JWT = require('jsonwebtoken'),
Cuid = require('cuid'),
Mongoose = require('mongoose'),
APIKeySchema = require('./models/apiKey').modelSchema,
LockSchema = require('./models/lock').modelSchema,
StateSchema = require('./models/state').modelSchema;
/**
* Models
*
* @ignore
*/
var APIKey = Mongoose.model('APIKey', APIKeySchema),
Lock = Mongoose.model('Lock', LockSchema),
State = Mongoose.model('State', StateSchema);
/**
* Private
*
* @ignore
*/
function onError(err) {
console.error('DB-MONGO: Error occurred connecting to database.', err);
}
function onDisconnect() {
console.warn('DB-MONGO: Connection lost, will retry automatically.');
}
function onReconnect() {
}
var db = {
/**
* Establishes a persistent connection the underlying MongoDB database.
* Called during application startup.
*
* @method connect
* @async
* @param {Function} [callback] Optional callback function to determine when the connection has completed and if it was successful.
*/
connect: function (callback) {
var options = {
server: {
/* @ignore */
/* jshint camelcase: false */
auto_reconnect: true,
socketOptions: {
keepAlive: 1
}
}
};
Mongoose.connection.on('error', onError);
if (!process.env.MONGO) {
console.warn('DB-MONGO: MONGO environment variable has not been set, will use localhost.');
}
var connectionString = process.env.MONGO || 'mongodb://localhost/hashdo';
console.log('DB-MONGO: Connecting to ' + connectionString);
Mongoose.connect(connectionString, options, function (err) {
if (!err) {
console.log('DB-MONGO: Successfully connected to the database.');
Mongoose.connection.on('reconnected', onReconnect);
Mongoose.connection.on('disconnected', onDisconnect);
}
else {
console.log('DB-MONGO: Could not connect to database.');
}
callback && callback(err);
});
},
/**
* Closes all connections to the database and de-registers from event handlers.
* Called during application shutdown.
*
* @method disconnect
* @async
* @param {Function} [callback] Optional callback function to determine when the connection has been closed.
*/
disconnect: function (callback) {
Mongoose.connection.removeListener('reconnected', onReconnect);
Mongoose.connection.removeListener('disconnected', onDisconnect);
Mongoose.connection.close(callback);
},
/**
* Save the state object of a card to the database.
* Using the same card key will overwrite existing data.
*
* @method saveCardState
* @async
* @param {String} cardKey The unique key assigned to the card, this is normally accessible from inputs.cardKey in the card handler function.
* @param {Object} value JSON object of any state data that needs to be persisted to the database.
* @param {Function} [callback] Optional callback function to determine when the data has been saved or failed to save.
*/
saveCardState: function (cardKey, value, callback) {
State.findOneAndUpdate({cardKey: cardKey}, {value: value, dateTimeStamp: Date.now()}, {upsert: true}, function (err) {
callback && callback(err);
});
},
/**
* Retrieve existing card state from the database.
*
* @method getCardState
* @async
* @param {String} cardKey The unique key assigned to the card, this is normally accessible from inputs.cardKey in the card handler function.
* @param {String} legacyCardKey The legacy key assigned to the card, this is normally accessible from inputs.legacyCardKey in the card handler function.
* @param {Function} [callback] Callback function to retrieve the JSON object state data.
*/
getCardState: function (cardKey, legacyCardKey, callback) {
State.load(cardKey, function (err, value) {
if (!err) {
// Couldn't find new key? Try the old one if it was provided.
if (!value && legacyCardKey) {
State.load(legacyCardKey, function (err, value) {
callback && callback(err, value);
});
}
else {
callback && callback(null, value);
}
}
else {
callback && callback(err, null);
}
});
},
/**
* Create an assign a API call key to a specific card.
* This key will be required to decode and secure parameters.
*
* @method issueAPIKey
* @async
* @param {String} cardKey The unique key assigned to the card, this is normally accessible from inputs.cardKey in the card handler function.
* @param {Function} [callback] Callback function to retrieve the new API key.
*/
issueAPIKey: function (cardKey, callback) {
APIKey.load(cardKey, function (err, key) {
if (key) {
callback && callback(err, key);
}
else {
var newKey = Cuid(),
apiKey = new APIKey({
cardKey: cardKey,
apiKey: newKey
});
apiKey.save(function (err) {
callback && callback(err, newKey);
});
}
});
},
/**
* Validate an API key against an existing card.
*
* @method validateAPIKey
* @async
* @param {String} cardKey The unique key assigned to the card, this is normally accessible from inputs.cardKey in the card handler function.
* @param {String} apiKey The API key assigned to the card, this is normally accessible from inputs.token in the card handler function.
* @param {Function} [callback] Callback function to retrieve the boolean value of whether the API key is valid.
*/
validateAPIKey: function (cardKey, apiKey, callback) {
APIKey.load(cardKey, function (err, issuedAPIKey) {
if (issuedAPIKey === apiKey) {
callback && callback(err, true);
}
else {
callback && callback(err, false);
}
});
},
/**
* Protect any JSON payload using web token.
*
* @method lock
* @async
* @param {String} pack The pack name.
* @param {String} card The card name.
* @param {Object} payload JSON payload to protect. This will normally be secure card inputs and their values.
* @param {String} secretOrPrivateKey Must be either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA.
* @param {Function} [callback] Callback function to retrieve unique key required to unlock the data.
*/
lock: function (pack, card, payload, secretOrPrivateKey, callback) {
var key = Cuid(),
token = JWT.sign(payload, secretOrPrivateKey || '#');
var lock = new Lock({
pack: pack,
card: card,
key: key,
token: token
});
lock.save(function (err) {
callback && callback(err, key);
});
},
/**
* Decode previously protected JSON payload.
*
* @method unlock
* @async
* @param {String} pack The pack name.
* @param {String} card The card name.
* @param {String} key The unique key that was returned when locking the data.
* @param {String} secretOrPrivateKey Must be either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA.
* @param {Function} [callback] Callback function to retrieve decoded JSON payload.
*/
unlock: function (pack, card, key, secretOrPrivateKey, callback) {
Lock.load(pack, card, key, function (err, token) {
if (!err && token) {
JWT.verify(token, secretOrPrivateKey || '#', function (err, decoded) {
callback && callback(err, decoded);
});
}
else {
callback && callback(err);
}
});
}
};
/**
* Exports
*
* @ignore
*/
module.exports = db;