-
Notifications
You must be signed in to change notification settings - Fork 1
/
safe.js
313 lines (281 loc) · 8.72 KB
/
safe.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
/* global SimpleSchema, FlashNotifications, ValidationError, console */
/* global Safe:true */
/** @namespace */
Safe = {};
/**
* Cleans + Validates the doc (in place) according to a SimpleSchema.
* @param {Object} docOrMod - The document or modifier to use.
* @param {SimpleSchema} simpleSchema - The SS to use for validation.
* @param {Object} options - Options.
* @throws An error object with deails like {fieldName: errorString}
* when validation fails.
* @returns {undefined} If the document validates.
*/
Safe.validate = function(docOrMod, simpleSchema, options) {
check(docOrMod, Object);
check(simpleSchema, SimpleSchema);
options = _.extend({
isModifier: false,
context: simpleSchema.newContext(),
logErrors: false
}, options);
check(options, {
// Is docOrMod a modifier?
isModifier: Boolean,
// SimpleSchemaValidationContext (SS doesn't export the symbol)
context: simpleSchema.newContext().constructor,
logErrors: Boolean
});
// If the schema includes a 'prepare' hook, run it.
if (_.isFunction(simpleSchema.prepare)) {
var doc = docOrMod;
var params = {isUpdate: false};
if (options.isModifier) {
doc = docOrMod.$set || {};
params = {
isUpdate: true,
modifier: docOrMod
};
}
// The attributes we're setting. If the operation is modifier, and there is
// a $set component, this will be it.
check(doc, Object);
check(params, {
// Are we doing an update?
isUpdate: Boolean,
// If we have a modifier, it's in here
modifier: Match.Optional(Object)
});
simpleSchema.prepare(doc, params);
}
simpleSchema.clean(docOrMod, {isModifier: options.isModifier, filter: false,
trimString: false});
if (!options.context.validate(docOrMod, {modifier: options.isModifier})) {
var errors = {};
_.each(options.context.getErrorObject().invalidKeys, function(x) {
errors[x.name] = x;
});
if (options.logErrors) {
Log.error("Validation Errors:");
Log.error(errors);
}
throw new Safe.ValidationError(errors);
}
};
/**
* Throws a ForbiddenError if you're not logged in.
* @returns {void}
*/
Safe.checkLoggedIn = function() {
if (!Meteor.userId()) {
throw new Safe.ForbiddenError("You must be logged in");
}
};
/**
* Wraps Meteor.subscribe and logs a notification if there was an error
* @param {...*} arguments - @see Meteor.subscribe
* @returns {*} @see Meteor.subscribe
*/
Safe.subscribe = function() {
var args = Array.prototype.slice.call(arguments);
var final = _.last(args);
var callbacks = {};
// If callbacks are present, save a reference and remove them from args
if (_.isObject(final)
&& (_.isFunction(final.onReady) || _.isFunction(final.onError))) {
_.extend(callbacks, final);
args.pop();
}
else if (_.isFunction(final)) {
callbacks.onReady = final;
args.pop();
}
args.push({
onReady: function() {
if (_.isFunction(callbacks.onReady)) {
callbacks.onReady.call();
}
},
onError: function() {
Log.error(arguments);
FlashNotifications.add({
title: "Subscription Error",
description: "Failed to to subscribe to '" + _.first(args) + "'",
icon: "alert",
feeling: "negative"
});
if (_.isFunction(callbacks.onError)) {
callbacks.onError.apply(null, arguments);
}
}
});
return Meteor.subscribe.apply(null, args);
};
/**
* Wraps Meteor.call and logs a notification if there was an error
* @param {String} name Name of method to invoke
* @param {...*} arguments - @see Meteor.call
* @param {Function} callback - usually a Safe.okHandler, but optionally function(e, r)
* @returns {*} @see Meteor.call
*/
Safe.call = function (name) {
// if it's a function, the last argument is the result callback,
// not a parameter to the remote method.
var args = Array.prototype.slice.call(arguments, 1);
if (args.length && typeof args[args.length - 1] === "function") {
var callback = args.pop();
}
try {
Meteor.apply(name, args, {throwStubExceptions: true}, callback);
}
catch(e) {
callback(e);
}
};
// POC for the most basic of re-usable method handlers that corresponds to our
// proposed generic return interface for mutating methods
if (Meteor.isServer) {
// On the server we throw when not ok
Safe.okHandler = function(okCb) {
return function(e, r) {
if (e) {
/* eslint-disable no-console */
console.error(e.details);
/* eslint-enable no-console */
throw e;
}
else if (_.isFunction(okCb)) {
okCb(r);
}
};
};
}
else {
// On the client use Flash Notifications
Safe.okHandler = function(errors, okCb) {
if (_.isFunction(errors)) {
okCb = errors;
errors = null;
}
return function(e, r) {
var report = function(log, description, title) {
title = title || "Operation Failed";
/* eslint-disable no-console */
if (log) {
console.error(log);
}
if (description) {
console.error(description);
}
/* eslint-enable no-console */
FlashNotifications.add({
title: title,
description: description,
icon: "alert",
feeling: "negative"
});
};
if (!e) {
if (_.isFunction(okCb)) {
okCb(r);
}
}
else if (e.error === "validation-failed") {
if (errors) {
errors.resetValidation();
errors.addInvalidKeys(_.values(e.details));
}
var count = _.keys(e.details).length;
var details = count + " form " + (count !== 1 ? "errors" : "error") + ", please review";
report(e.details, details, "Validation Error");
}
else if (e instanceof Match.Error) {
report("Match Failed", "Validation error");
}
else {
var message = e.reason || "";
if (e.details) {
message += ", " + e.details;
}
report(e, message);
}
};
};
}
Safe.Match = {};
/**
* Will match an object optionally containing only keys from a whitelist.
* @param {Array} allowedKeys - The whitelisted keys.
* @returns {boolean} true if the object passes the test.
*/
Safe.Match.WhitelistedObject = function(allowedKeys) {
return Match.Where(function(x) {
var schema = {};
_.each(allowedKeys, function(key) {
schema[key] = Match.Optional(Match.Any);
});
check(x, schema);
return true;
});
};
Safe.Match.RegEx = function(exp) {
return Match.Where(function(x) {
return x.match(exp);
});
};
// Optional but `undefined` is allowed
Safe.Match.TemplateOptional = function(pattern) {
return Match.Optional(Match.Where(function (x) {
if (_.isUndefined(x)) {
return true;
}
check(x, pattern);
return true;
}));
};
Safe.SimpleSchema = {
RegEx: {
// Old id's we have lying around for some imported data that contain 0's
// and 1's unlike Meteor's ids which don't
OldId: /^[0123456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz]{17}$/,
// Taken from https://gist.github.com/dperini/729294/543514ef4ef5be998de55bf11349298459925cbe
// This is the same RegExp that SimpleSchema uses but we've made the TLD
// optional, thus allowing localhost urls to pass the regular expression
Url: new RegExp(
"^"
// protocol identifier
+ "(?:(?:https?|ftp)://)"
// user:pass authentication
+ "(?:\\S+(?::\\S*)?@)?"
+ "(?:"
// IP address exclusion
// private & local networks
+ "(?!(?:10|127)(?:\\.\\d{1,3}){3})"
+ "(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})"
+ "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})"
// IP address dotted notation octets
// excludes loopback network 0.0.0.0
// excludes reserved space >= 224.0.0.0
// excludes network & broacast addresses
// (first & last IP address of each class)
+ "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])"
+ "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}"
+ "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))"
+ "|"
// host name
+ "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)"
// domain name
+ "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*"
// TLD identifier
+ "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))?"
+ ")"
// port number
+ "(?::\\d{2,5})?"
// resource path
+ "(?:/\\S*)?"
+ "$", "i"
),
// Stricter version than is included with SimpleSchema
Email: /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9]{2,}(?:[a-z0-9-]*[a-z0-9])?$/i
}
};