forked from pencilblue/pencilblue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base_controller.js
executable file
·495 lines (440 loc) · 15.9 KB
/
base_controller.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
/*
Copyright (C) 2015 PencilBlue, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//dependencies
var url = require('url');
var util = require('../include/util.js');
module.exports = function BaseControllerModule(pb) {
/**
* The base controller provides functions for the majority of
* the heavy lifing for a controller. It accepts and provides access to
* extending controllers for items such as the request, response, session, etc.
* @class BaseController
* @constructor
*/
function BaseController(){}
//constants
/**
* The code for a successful API call
* @static
* @property API_SUCCESS
* @type {Integer}
*/
BaseController.API_SUCCESS = 0;
/**
* The code for a failed API call
* @static
* @property API_FAILURE
* @type {Integer}
*/
BaseController.API_FAILURE = 1;
/**
* The snippet of JS code that will ensure that a form is refilled with values
* from the post
* @static
* @private
* @property FORM_REFILL_PATTERN
* @type {String}
*/
var FORM_REFILL_PATTERN = 'if(typeof refillForm !== "undefined") {' + "\n" +
'$(document).ready(function(){'+ "\n" +
'refillForm(%s)});}';
/**
* The snippet of HTML that will display an alert box
* @static
* @private
* @property ALERT_PATTERN
* @type {String}
*/
var ALERT_PATTERN = '<div class="alert %s error_success">%s<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button></div>';
/**
* A mapping that converts the HTTP standard for content-type encoding and
* what the Buffer prototype expects
* @static
* @private
* @readonly
* @property ENCODING_MAPPING
* @type {Object}
*/
var ENCODING_MAPPING = Object.freeze({
'UTF-8': 'utf8',
'US-ASCII': 'ascii',
'UTF-16LE': 'utf16le'
});
/**
* Responsible for initializing a controller. Properties from the
* RequestHandler are passed down so that the controller has complete access to
* a variety of request specified properties. By default the function transfers the options over to instance variables that can be access during rendering. In addition, the function sets up the template service along with a set of local flags:
* <ul>
* <li>locale - The selected locale for the request (NOTE: this may not match the requested language if not supported)</li>
* <li>error_success - An alert box if one was registered by the controller</li>
* <li>page_name - The title of the page</li>
* <li>localization_script - Includes the localization script so that it can be used client side</li>
* <li>analytics - Inserts the necessary javascript for analytics providers</li>
* </ul>
* @method init
* @param {Object} props The properties needed to initialize the controller
* @param {RequestHandler} props.request_handler
* @param {Request} props.request The incoming request
* @param {Response} props.response The outgoing response
* @param {Object} props.session The session object
* @param {Localization} props.localization_service The localization service instance for the request
* @param {Object} props.path_vars The path variables associated with the URL for the request
* @param {Object} props.query The query string variables associated with the URL for the request
* @param {Function} cb A callback that takes a single optional argument: cb(Error)
*/
BaseController.prototype.init = function(props, cb) {
this.reqHandler = props.request_handler;
this.req = props.request;
this.res = props.response;
this.session = props.session;
this.body = props.body;
this.localizationService = props.localization_service;
this.ls = this.localizationService;
this.pathVars = props.path_vars;
this.query = props.query;
this.pageName = '';
var self = this;
var tsOpts = {
ls: this.localizationService,
activeTheme: props.activeTheme
};
this.templateService = new pb.TemplateService(tsOpts);
this.templateService.registerLocal('locale', this.ls.language);
this.templateService.registerLocal('error_success', function(flag, cb) {
self.displayErrorOrSuccessCallback(flag, cb);
});
this.templateService.registerLocal('page_name', function(flag, cb) {
cb(null, self.getPageName());
});
this.templateService.registerLocal('localization_script', function(flag, cb) {
self.requiresClientLocalizationCallback(flag, cb);
});
this.templateService.registerLocal('analytics', function(flag, cb) {
pb.AnalyticsManager.onPageRender(self.req, self.session, self.ls, cb);
});
this.templateService.registerLocal('wysiwyg', function(flag, cb) {
var wysiwygId = util.uniqueId();
self.templateService.registerLocal('wys_id', wysiwygId);
self.templateService.load('admin/elements/wysiwyg', function(err, data) {
cb(err, new pb.TemplateValue(data, false));
});
});
this.ts = this.templateService;
/**
*
* @property activeTheme
* @type {String}
*/
this.activeTheme = props.activeTheme;
//build out a base service context that can be cloned and passed to any
//service objects
this.context = {
req: this.req,
session: this.session,
ls: this.ls,
ts: this.ts,
activeTheme: this.activeTheme
};
cb();
};
/**
* Retrieves a context object that contains the necessary information for
* service prototypes
* @method getServiceContext
* @return {Object}
*/
BaseController.prototype.getServiceContext = function(){
return util.merge(this.context, {});
};
/**
*
* @method requiresClientLocalization
* @return {Boolean}
*/
BaseController.prototype.requiresClientLocalization = function() {
return true;
};
/**
*
* @method requiresClientLocalizationCallback
* @param {String} flag
* @param {Function} cb
*/
BaseController.prototype.requiresClientLocalizationCallback = function(flag, cb) {
var val = '';
if (this.requiresClientLocalization()) {
val = pb.ClientJs.includeJS('/api/localization/script');
}
cb(null, new pb.TemplateValue(val, false));
};
/**
*
* @method formError
* @param {String} message The error message to be displayed
* @param {String} redirectLocation
* @param {Function} cb
*/
BaseController.prototype.formError = function(message, redirectLocation, cb) {
this.session.error = message;
var uri = pb.UrlService.createSystemUrl(redirectLocation);
cb(pb.RequestHandler.generateRedirect(uri));
};
/**
*
* @method displayErrorOrSuccessCallback
* @param {String} flag
* @param {Function} cb
*/
BaseController.prototype.displayErrorOrSuccessCallback = function(flag, cb) {
if(this.session.error) {
var error = this.session.error;
delete this.session.error;
cb(null, new pb.TemplateValue(util.format(ALERT_PATTERN, 'alert-danger', this.localizationService.get(error)), false));
}
else if(this.session.success) {
var success = this.session.success;
delete this.session.success;
cb(null, new pb.TemplateValue(util.format(ALERT_PATTERN, 'alert-success', this.localizationService.get(success)), false));
}
else {
cb(null, '');
}
};
/**
* Provides a page title. This is picked up by the template engine when the
* ^page_name^ key is found in a template.
* @method getPageName
* @return {String} The page title
*/
BaseController.prototype.getPageName = function() {
return this.pageName;
};
/**
* Sets the page title
* @method setPageName
* @param {String} pageName The desired page title
*/
BaseController.prototype.setPageName = function(pageName) {
this.pageName = pageName;
};
/**
*
* @method getPostParams
* @param {Function} cb
*/
BaseController.prototype.getPostParams = function(cb) {
var self = this;
this.getPostData(function(err, raw){
if (util.isError(err)) {
cb(err, null);
return;
}
//lookup encoding
var encoding = pb.BaseBodyParser.getContentEncoding(self.req);
encoding = ENCODING_MAPPING[encoding] ? ENCODING_MAPPING[encoding] : 'utf8';
//convert to string
var postParams = url.parse('?' + raw.toString(encoding), true).query;
cb(null, postParams);
});
};
/**
* Parses the incoming payload of a request as JSON formatted data.
* @method getJSONPostParams
* @param {Function} cb
*/
BaseController.prototype.getJSONPostParams = function(cb) {
var self = this;
this.getPostData(function(err, raw){
if (util.isError(err)) {
return cb(err, null);
}
//lookup encoding
var encoding = pb.BaseBodyParser.getContentEncoding(self.req);
encoding = ENCODING_MAPPING[encoding] ? ENCODING_MAPPING[encoding] : 'utf8';
var error = null;
var postParams = null;
try {
postParams = JSON.parse(raw.toString(encoding));
}
catch(err) {
error = err;
}
cb(error, postParams);
});
};
/**
*
* @method getPostData
* @param {Function} cb
*/
BaseController.prototype.getPostData = function(cb) {
var buffers = [];
var totalLength = 0;
this.req.on('data', function (data) {
buffers.push(data);
totalLength += data.length;
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (totalLength > 1e6) {
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
var err = new Error("POST limit reached! Maximum of 1MB.");
err.code = 400;
cb(err, null);
}
});
this.req.on('end', function () {
//create one big buffer.
var body = Buffer.concat (buffers, totalLength);
cb(null, body);
});
};
/**
*
* @method hasRequiredParams
* @param {Object} queryObject
* @param {Array} requiredParameters
*/
BaseController.prototype.hasRequiredParams = function(queryObject, requiredParameters) {
for (var i = 0; i < requiredParameters.length; i++) {
if (typeof queryObject[requiredParameters[i]] === 'undefined') {
return this.localizationService.get('FORM_INCOMPLETE');
}
else if (queryObject[requiredParameters[i]].length === 0) {
return this.localizationService.get('FORM_INCOMPLETE');
}
}
if(queryObject.password && queryObject.confirm_password) {
if(queryObject.password !== queryObject.confirm_password) {
return this.localizationService.get('PASSWORD_MISMATCH');
}
}
return null;
};
/**
*
* @method setFormFieldValues
* @param {Object} post
*/
BaseController.prototype.setFormFieldValues = function(post) {
this.session.fieldValues = post;
return this.session;
};
/**
*
* @method checkForFormRefill
* @param {String} result
* @param {Function} cb
*/
BaseController.prototype.checkForFormRefill = function(result, cb) {
if(this.session.fieldValues) {
var content = util.format(FORM_REFILL_PATTERN, JSON.stringify(this.session.fieldValues));
var formScript = pb.ClientJs.getJSTag(content);
result = result.concat(formScript);
delete this.session.fieldValues;
}
cb(result);
};
/**
* Sanitizes an object. This function is handy for incoming post objects. It
* iterates over each field. If the field is a string value it will be
* sanitized based on the default sanitization rules
* (BaseController.getDefaultSanitizationRules) or those provided by the call
* to BaseController.getSanitizationRules.
* @method sanitizeObject
* @param {Object} obj
*/
BaseController.prototype.sanitizeObject = function(obj) {
if (!util.isObject(obj)) {
return;
}
var rules = this.getSanitizationRules();
for(var prop in obj) {
if (util.isString(obj[prop])) {
var config = rules[prop];
obj[prop] = BaseController.sanitize(obj[prop], config);
}
}
};
/**
*
* @method getSanitizationRules
* @return {Object}
*/
BaseController.prototype.getSanitizationRules = function() {
return {};
};
/**
* The sanitization rules that apply to Pages and Articles
* @deprecated Since 0.4.1
* @static
* @method getContentSanitizationRules
*/
BaseController.getContentSanitizationRules = function() {
return pb.BaseObjectService.getContentSanitizationRules();
};
/**
* @deprecated Since 0.4.1
* @static
* @method getDefaultSanitizationRules
*/
BaseController.getDefaultSanitizationRules = function() {
return pb.BaseObjectService.getDefaultSanitizationRules();
};
/**
*
* @deprecated Since 0.4.1
* @static
* @method sanitize
* @param {String} value
* @param {Object} [config]
*/
BaseController.sanitize = function(value, config) {
return pb.BaseObjectService.sanitize(value, config);
};
/**
* Redirects a request to a different location
* @method redirect
* @param {String} location
* @param {Function} cb
*/
BaseController.prototype.redirect = function(location, cb){
cb(pb.RequestHandler.generateRedirect(location));
};
/**
* Generates an generic API response object
* @static
* @method apiResponse
* @return {String} JSON
*/
BaseController.apiResponse = function(cd, msg, dta) {
if(typeof msg === 'undefined') {
switch(cd) {
case BaseController.FAILURE:
msg = 'FAILURE';
break;
case BaseController.SUCCESS:
msg = 'SUCCESS';
break;
default:
msg = '';
break;
}
}
if(typeof dta === 'undefined') {
dta = null;
}
var response = {code: cd, message: msg, data: dta};
return JSON.stringify(response);
};
return BaseController;
};