/
mixins.js
347 lines (297 loc) · 7.73 KB
/
mixins.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
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
'use strict';
var _ = require('lodash');
var uuid = require('uuid');
var moment = require('moment');
var accounting = require('accounting');
var URLSafeBase64 = require('urlsafe-base64');
var crypto = require('crypto');
var mongodb = require('mongodb');
var debug = require('./debug');
module.exports = {
// Export Dependencies
Promise: require('bluebird'),
Backbone: require('backbone'),
express: require('express'),
request: require('request'),
mongodb: mongodb,
moment: moment,
accounting: accounting,
uuid: uuid,
_: _,
// Export Logging Methods
debug: debug,
log: debug.log,
error: debug.error,
warn: debug.warn,
info: debug.info,
// Proxy for Lodash
isError: _.isError,
// Proxy for MongoDB
ObjectId: mongodb.ObjectID,
/**
* Determine if a value is null or undefined
*
* @param {*} val
* @return {Boolean}
*/
isNullOrUndefined: function(val) {
return _.isNull(val) || _.isUndefined(val);
},
/**
* Check if a string is a valid ObjectId
*
* @param {String} id
* @return {Boolean}
*/
isObjectId: function(id) {
// Check if a string is a valid ObjectId
return require('mongodb-objectid-helper').isObjectId(id);
},
/**
* Create and return an ObjectId as a BSON object
*
* @param {String} [str]
* @return {BSON}
*/
newObjectId: function(str) {
return new this.ObjectId(str);
},
/**
* Create and return an ObjectId as a hex string
*
* @param {String} [str]
* @return {String}
*/
newObjectIdHexString: function(str) {
return new this.ObjectId(str).toHexString();
},
/**
* Convert cents to dollars with 2 decimal points and no thousand separator
*
* Example: `1234 -> 12.34`
*
* @param {Number} value
* @return {Number}
*/
centsToDollars: function(value) {
return parseFloat(accounting.toFixed(value / 100, 2));
},
/**
* Convert dollars to cents
*
* Example: `12.34 -> 1234`
*
* @param {Number} value
* @return {Number}
*/
dollarsToCents: function(value) {
return _.parseInt(accounting.toFixed(accounting.unformat(value) * 100, 0));
},
/**
* Encrypts a utf8 string into an encrypted hex string
*
* Useful for encrypting strings that later need to be decrypted
*
* https://github.com/joyent/node/issues/6386
*
* @param {String} str
* @param {String} [algorithm=aes256]
* @param {String} [key=...]
* @return {String}
*/
encryptString: function(str, algorithm, key) {
var inputEncoding = 'utf8';
var outputEncoding = 'hex';
algorithm = algorithm || 'aes256';
// Obviously don't reuse this key
key = key || '13741c7ec3a809950ed8e75c1abcfa0e8f9994b2b79d7a895c2e383f28c8a792';
var cipher = crypto.createCipher(algorithm, key);
var ciphered = cipher.update(str, inputEncoding, outputEncoding);
ciphered += cipher.final(outputEncoding);
return ciphered;
},
/**
* Decrypts an encrypted hex string back into a utf8 string
*
* https://github.com/joyent/node/issues/6386
*
* @param {} str
* @param {} [algorithm=aes256]
* @param {} [key=...]
* @return {String}
*/
decryptString: function(str, algorithm, key) {
var inputEncoding = 'utf8';
var outputEncoding = 'hex';
algorithm = algorithm || 'aes256';
// Obviously don't reuse this key
key = key || '13741c7ec3a809950ed8e75c1abcfa0e8f9994b2b79d7a895c2e383f28c8a792';
var decipher = crypto.createDecipher(algorithm, key);
var deciphered = decipher.update(str, outputEncoding, inputEncoding);
deciphered += decipher.final(inputEncoding);
return deciphered;
},
/**
* Encodes a string into a URL safe Base64 string
*
* @param {String} str
* @return {String}
*/
encodeBase64: function(str) {
return URLSafeBase64.encode(new Buffer(str, 'utf-8'));
},
/**
* Decode a URL safe Base64 string
*
* @param {String} str
* @return {String}
*/
decodeBase64: function(str) {
return URLSafeBase64.decode(str).toString('utf-8');
},
/**
* Determine if a string is URL safe Base64
*
* @param {String} str
* @return {Boolean}
*/
validateBase64: function(str) {
return URLSafeBase64.validate(str);
},
/**
* Determine if a string is a UUID
*
* http://en.wikipedia.org/wiki/Universally_unique_identifier#Variants_and_versions
*
* Supports Version 3 (MD5 hash)
* xxxxxxxx-xxxx-3xxx-yxxx-xxxxxxxxxxxx
* where x is any hexadecimal digit and y is one of 8, 9, A, or B
*
* Supports Version 4 (random)
* xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx / f47ac10b-58cc-4372-a567-0e02b2c3d479
* where x is any hexadecimal digit and y is one of 8, 9, A, or B
*
* @param {String} value
* @return {Boolean}
*/
isUUID: function(value) {
return /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i.test(value);
},
/**
* Check if a string is a unix timestamp in milliseconds
*
* @param {String} value
* @return {Boolean}
*/
isTimestamp: function(value) {
if (value && value >= 0 && value.toString().length === 13) {
return true;
}
return false;
},
/**
* Check if a string is in ISO8601 date format
*
* Examples:
*
* - YYYY-MM-DDTHH:mm:ss.SSSZ
* - 2013-11-18T09:04:24.447Z
*
* @param {String} str
* @return {Boolean}
*/
isValidISO8601String: function(str) {
// 2013-11-18T09:04:24.447Z
// YYYY-MM-DDTHH:mm:ss.SSSZ
return moment.utc(str, 'YYYY-MM-DDTHH:mm:ss.SSSZ', true).isValid();
},
/**
* Determine if a number is a unix timestamp in seconds
*
* Min: 1000000000 (Sun, 09 Sep 2001 01:46:40 GMT)
* Max: 2147483647 (Tue, 19 Jan 2038 03:14:07 GMT)
*
* @param {Number} value
* @return {Boolean}
*/
isUnixTime: function(value) {
value = _.parseInt(value);
if (!_.isNaN(value) && value.toString().length === 10) {
return true;
}
return false;
},
/**
* Determine if a number is a unix timestamp in milliseconds
*
* Min: 1000000000000 (Sun, 09 Sep 2001 01:46:40 GMT)
* Max: 2147483647000 (Tue, 19 Jan 2038 03:14:07 GMT)
*
* @param {Number} value
* @return {Boolean}
*/
isUnixTimeMilliseconds: function(value) {
value = _.parseInt(value);
if (!_.isNaN(value) && value.toString().length === 13) {
return true;
}
return false;
},
/**
* Trim, Remove Whitespace, and Lowercase an email
*
* @param {String} email
* @return {String}
*/
sanitizeEmail: function(email) {
return email.trim().toLowerCase().replace(/\s/g, '');
},
/**
* Determine if a string is a valid email
*
* @param {String} email
* @return {Boolean}
*/
isValidEmail: function(email) {
if (email &&
typeof(email) === 'string' &&
email.length > 0 &&
email.match(/^(|(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,12})$/i)) {
return true;
} else {
return false;
}
},
/**
* Escape special characters for use in Mongo query
*
* @param {String} str
* @return {String}
*/
escapeRegExp: function(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
},
/**
* Turns an Object into a hashed String
*
* @param {Object} object
* @param {String} [algorithm=sha1]
* @return {String}
*/
fingerprintObject: function(object, algorithm) {
algorithm = algorithm || 'sha1';
return crypto.createHash(algorithm)
.update(JSON.stringify(object))
.digest('hex')
.toString();
},
/**
* Randomly generates a `sha256` hashed hex String
* Uses `uuid.v4` as the seed
*
* @return {String}
*/
randomHash: function() {
return crypto.createHash('sha256').update(uuid.v4()).digest('hex');
}
};