forked from keystonejs/keystone-classic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1752 lines (1411 loc) · 43.6 KB
/
index.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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var fs = require('fs'),
path = require('path'),
http = require('http'),
https = require('https'),
_ = require('underscore'),
express = require('express'),
async = require('async'),
jade = require('jade'),
moment = require('moment'),
numeral = require('numeral'),
cloudinary = require('cloudinary'),
mandrillapi = require('mandrill-api'),
utils = require('keystone-utils');
var templateCache = {};
var dashes = '\n------------------------------------------------\n';
/**
* Don't use process.cwd() as it breaks module encapsulation
* Instead, let's use module.parent if it's present, or the module itself if there is no parent (probably testing keystone directly if that's the case)
* This way, the consuming app/module can be an embedded node_module and path resolutions will still work
* (process.cwd() breaks module encapsulation if the consuming app/module is itself a node_module)
*/
var moduleRoot = (function(_rootPath) {
var parts = _rootPath.split(path.sep);
parts.pop(); //get rid of /node_modules from the end of the path
return parts.join(path.sep);
})(module.parent ? module.parent.paths[0] : module.paths[0]);
/**
* Keystone Class
*
* @api public
*/
var Keystone = function() {
this.lists = {};
this.paths = {};
this._options = {
'name': 'Keystone',
'brand': 'Keystone',
'compress': true,
'headless': false,
'logger': 'dev',
'auto update': false,
'model prefix': null
};
this._pre = {
routes: [],
render: []
};
this._redirects = {};
// expose express
this.express = express;
// init environment defaults
this.set('env', process.env.NODE_ENV || 'development');
this.set('port', process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT);
this.set('host', process.env.HOST || process.env.IP || process.env.OPENSHIFT_NODEJS_IP);
this.set('listen', process.env.LISTEN);
this.set('ssl', process.env.SSL);
this.set('ssl port', process.env.SSL_PORT);
this.set('ssl host', process.env.SSL_HOST || process.env.SSL_IP);
this.set('ssl key', process.env.SSL_KEY);
this.set('ssl cert', process.env.SSL_CERT);
this.set('cookie secret', process.env.COOKIE_SECRET);
this.set('embedly api key', process.env.EMBEDLY_API_KEY || process.env.EMBEDLY_APIKEY);
this.set('mandrill api key', process.env.MANDRILL_API_KEY || process.env.MANDRILL_APIKEY);
this.set('mandrill username', process.env.MANDRILL_USERNAME);
this.set('google api key', process.env.GOOGLE_BROWSER_KEY);
this.set('google server api key', process.env.GOOGLE_SERVER_KEY);
this.set('ga property', process.env.GA_PROPERTY);
this.set('ga domain', process.env.GA_DOMAIN);
this.set('chartbeat property', process.env.CHARTBEAT_PROPERTY);
this.set('chartbeat domain', process.env.CHARTBEAT_DOMAIN);
this.set('allowed ip ranges', process.env.ALLOWED_IP_RANGES);
if (process.env.S3_BUCKET && process.env.S3_KEY && process.env.S3_SECRET) {
this.set('s3 config', { bucket: process.env.S3_BUCKET, key: process.env.S3_KEY, secret: process.env.S3_SECRET, region: process.env.S3_REGION });
}
if (process.env.AZURE_STORAGE_ACCOUNT && process.env.AZURE_STORAGE_ACCESS_KEY) {
this.set('azurefile config', { account: process.env.AZURE_STORAGE_ACCOUNT, key: process.env.AZURE_STORAGE_ACCESS_KEY });
}
if (process.env.CLOUDINARY_URL) {
// process.env.CLOUDINARY_URL is processed by the cloudinary package when this is set
this.set('cloudinary config', true);
}
this.initAPI = require('./lib/middleware/initAPI')(this);
};
/**
* Deprecated options that have been mapped to new keys
*/
var remappedOptions = {
'signin success': 'signin redirect',
'signout': 'signout url'
};
/**
* Sets keystone options
*
* ####Example:
*
* keystone.set('user model', 'User') // sets the 'user model' option to `User`
*
* @param {String} key
* @param {String} value
* @api public
*/
Keystone.prototype.set = function(key, value) {
if (arguments.length === 1) {
return this._options[key];
}
if (remappedOptions[key]) {
if (this.get('logger')) {
console.log('\nWarning: the `' + key + '` option has been deprecated. Please use `' + remappedOptions[key] + '` instead.\n\n' +
'Support for `' + key + '` will be removed in a future version.');
}
key = remappedOptions[key];
}
// handle special settings
switch (key) {
case 'cloudinary config':
if (_.isObject(value)) {
cloudinary.config(value);
}
value = cloudinary.config();
break;
case 'mandrill api key':
if (value) {
this.mandrillAPI = new mandrillapi.Mandrill(value);
}
break;
case 'auth':
if (value === true && !this.get('session')) {
this.set('session', true);
}
break;
case 'nav':
this.nav = this.initNav(value);
break;
case 'mongo':
if ('string' !== typeof value) {
if (Array.isArray(value) && (value.length === 2 || value.length === 3)) {
console.log('\nWarning: using an array for the `mongo` option has been deprecated.\nPlease use a mongodb connection string, e.g. mongodb://localhost/db_name instead.\n\n' +
'Support for arrays as the `mongo` setting will be removed in a future version.');
value = (value.length === 2) ? 'mongodb://' + value[0] + '/' + value[1] : 'mongodb://' + value[0] + ':' + value[2] + '/' + value[1];
} else {
console.error('\nInvalid Configuration:\nThe `mongo` option must be a mongodb connection string, e.g. mongodb://localhost/db_name\n');
process.exit(1);
}
}
break;
}
this._options[key] = value;
return this;
};
/**
* Sets multiple keystone options.
*
* ####Example:
*
* keystone.set({test: value}) // sets the 'test' option to `value`
*
* @param {Object} options
* @api public
*/
Keystone.prototype.options = function(options) {
if (!arguments.length)
return this._options;
if (utils.isObject(options)) {
var keys = Object.keys(options),
i = keys.length,
k;
while (i--) {
k = keys[i];
this.set(k, options[k]);
}
}
return this._options;
};
/**
* Gets keystone options
*
* ####Example:
*
* keystone.get('test') // returns the 'test' value
*
* @param {String} key
* @method get
* @api public
*/
Keystone.prototype.get = Keystone.prototype.set;
/**
* Gets a path option, expanded to include moduleRoot if it is relative
*
* ####Example:
*
* keystone.get('test') // returns the 'test' value
*
* @param {String} key
* @method get
* @api public
*/
Keystone.prototype.getPath = function(key, defaultValue) {
var pathValue = keystone.get(key) || defaultValue;
pathValue = ('string' === typeof pathValue && pathValue.substr(0,1) !== path.sep && pathValue.substr(1,2) !== ':\\')
? path.join(moduleRoot, pathValue)
: pathValue;
return pathValue;
};
/**
* Registers a pre-event handler.
*
* Valid events include:
* - `routes` - calls the function before any routes are matched, after all other middleware
*
* @param {String} event
* @param {Function} function to call
* @api public
*/
Keystone.prototype.pre = function(event, fn) {
if (!this._pre[event]) {
throw new Error('keystone.pre() Error: event ' + event + ' does not exist.');
}
this._pre[event].push(fn);
return this;
};
/**
* Connects keystone to the application's mongoose instance.
*
* ####Example:
*
* var mongoose = require('mongoose');
*
* keystone.connect(mongoose);
*
* @param {Object} connections
* @api public
*/
Keystone.prototype.connect = function() {
// detect type of each argument
for (var i = 0; i < arguments.length; i++) {
if (arguments[i].constructor.name === 'Mongoose') {
// detected Mongoose
this.mongoose = arguments[i];
} else if (arguments[i].name === 'app') {
// detected Express app
this.app = arguments[i];
}
}
return this;
};
Keystone.prototype.prefixModel = function (key) {
var modelPrefix = this.get('model prefix');
if (modelPrefix)
key = modelPrefix + '_' + key;
return require('mongoose/lib/utils').toCollectionName(key);
}
/**
* The exports object is an instance of Keystone.
*
* @api public
*/
var keystone = module.exports = exports = new Keystone();
// Expose modules and Classes
keystone.utils = utils;
keystone.content = require('./lib/content');
keystone.List = require('./lib/list');
keystone.Field = require('./lib/field');
keystone.Field.Types = require('./lib/fieldTypes');
keystone.View = require('./lib/view');
keystone.Email = require('./lib/email');
/**
* Initialises Keystone in encapsulated mode.
*
* Creates an Express app and configures it if none has been connected.
*
* Also connects to the default mongoose instance if none has been connected.
*
* Accepts an options argument.
*
* Returns `this` to allow chaining.
*
* @param {Object} options
* @api public
*/
Keystone.prototype.init = function(options) {
this.options(options);
if (!this.app) {
this.app = express();
}
if (!this.mongoose) {
this.connect(require('mongoose'));
}
return this;
};
/**
* Initialises Keystone's nav
*
* @param {Object} nav
* @api private
*/
Keystone.prototype.initNav = function(sections) {
var nav = {
sections: [],
by: {
list: {},
section: {}
}
};
if (!sections) {
sections = {};
nav.flat = true;
_.each(this.lists, function(list) {
if (list.get('hidden')) return;
sections[list.path] = [list.path];
});
}
_.each(sections, function(section, key) {
if ('string' === typeof section) {
section = [section];
}
section = {
lists: section,
label: nav.flat ? keystone.list(section[0]).label : utils.keyToLabel(key)
};
section.key = key;
section.lists = _.map(section.lists, function(i) {
var msg, list = keystone.list(i);
if (!list) {
msg = 'Invalid Keystone Option (nav): list ' + i + ' has not been defined.\n';
throw new Error(msg);
}
if (list.get('hidden')) {
msg = 'Invalid Keystone Option (nav): list ' + i + ' is hidden.\n';
throw new Error(msg);
}
nav.by.list[list.key] = section;
return list;
});
if (section.lists.length) {
nav.sections.push(section);
nav.by.section[section.key] = section;
}
});
return nav;
};
/**
* Configures a Keystone app in encapsulated mode, but does not start it.
*
* Connects to the database and runs updates and then calls back.
*
* This is the code-path to use if you'd like to mount the keystone app as a sub-app in another express application.
*
* var app = express();
*
* //...do your normal express setup stuff, add middleware and routes (but not static content or error handling middleware yet)
*
* keystone.mount('/content', app, function() {
* //put your app's static content and error handling middleware here and start your server
* });
*
* Events are fired during initialisation to allow customisation, including:
*
* - onMount
*
* If the events argument is a function, it is assumed to be the mounted event.
*
*
* ####Options:
*
* Keystone supports the following options specifically for running in encapsulated mode (with no embedded server):
*
* - name
* - port
* - views
* - view engine
* - compress
* - favico
* - less
* - static
* - headless
* - logger
* - cookie secret
* - session
* - 404
* - 500
* - routes
* - locals
* - auto update
*
*
* @api public
*/
Keystone.prototype.mount = function(mountPath, parentApp, events) {
if (!this.app) {
throw new Error("KeystoneJS Initialisaton Error:\n\napp must be initialised. Call keystone.init() or keystone.connect(new Express()) first.\n\n");
}
if (arguments.length === 1) {
events = arguments[0];
mountPath = null;
}
if ('function' === typeof events) {
events = { onMount: events };
}
if (!events) events = {};
this.nativeApp = true;
var keystone = this,
app = this.app;
// default the mongo connection url
if (!this.get('mongo')) {
var dbName = this.get('db name') || utils.slug(this.get('name'));
var dbUrl = process.env.MONGO_URI || process.env.MONGO_URL || process.env.MONGOLAB_URI || process.env.MONGOLAB_URL || (process.env.OPENSHIFT_MONGODB_DB_URL || 'mongodb://localhost/') + dbName;
this.set('mongo', dbUrl);
}
/* Express sub-app mounting to external app at a mount point (if specified) */
if (mountPath) {
//fix root-relative keystone urls for assets (gets around having to re-write all the keystone templates)
parentApp.all(/^\/keystone($|\/*)/, function(req, res, next) {
req.url = mountPath + req.url;
next();
});
parentApp.use(mountPath, app);
}
/* Keystone's encapsulated Express App Setup */
// Allow usage of custom view engines
if (this.get('custom engine')) {
app.engine(this.get('view engine'), this.get('custom engine'));
}
// Set location of view templates and view engine
app.set('views', this.getPath('views') || path.sep + 'views');
app.set('view engine', this.get('view engine'));
// Apply locals
if (utils.isObject(this.get('locals'))) {
_.extend(app.locals, this.get('locals'));
}
if (this.get('env') !== 'production') {
app.set('view cache', this.get('view caching off') === undefined ? true : this.get('view caching off'));
app.locals.pretty = true;
}
// Serve static assets
if (this.get('compress')) {
app.use(express.compress());
}
if (this.get('favico')) {
app.use(express.favicon(this.getPath('favico')));
}
if (this.get('less')) {
app.use(require('less-middleware')({
src: this.getPath('less')
}));
}
if (this.get('sass')) {
try {
var sass = require('node-sass');
} catch(e) {
if (e.code == 'MODULE_NOT_FOUND') {
console.error(
'\nERROR: node-sass not found.\n' +
'\nPlease install the node-sass from npm to use the `sass` option.' +
'\nYou can do this by running "npm install node-sass --save".\n'
);
process.exit(1);
} else {
throw e;
}
}
app.use(sass.middleware({
src: this.getPath('sass'),
dest: this.getPath('sass'),
outputStyle: (this.get('env') == 'production') ? 'compressed' : 'nested'
}));
}
if (this.get('static')) {
app.use(express.static(this.getPath('static')));
}
if (!this.get('headless')) {
keystone.static(app);
}
// Handle dynamic requests
if (this.get('logger')) {
app.use(express.logger(this.get('logger')));
}
app.use(express.bodyParser());
app.use(express.methodOverride());
app.sessionOpts = {
key: 'keystone.sid',
cookieParser: express.cookieParser(this.get('cookie secret') === undefined ? 'keystone':this.get('cookie secret'))
};
app.use(app.sessionOpts.cookieParser);
if (this.get('session store') == 'mongo') {
var MongoStore = require('connect-mongo')(express);
app.sessionOpts.store = new MongoStore({
url: this.get('mongo'),
collection: 'app_sessions'
});
}
app.use(express.session(app.sessionOpts));
app.use(require('connect-flash')());
if (this.get('session') === true) {
app.use(this.session.persist);
} else if ('function' === typeof this.get('session')) {
app.use(this.get('session'));
}
// Process 'X-Forwarded-For' request header
if (this.get('trust proxy') === true) {
app.enable('trust proxy');
} else {
app.disable('trust proxy');
}
// Check for IP range restrictions
if (this.get('allowed ip ranges')) {
if (!app.get('trust proxy')) {
throw new Error("KeystoneJS Initialisaton Error:\n\nto set IP range restrictions the 'trust proxy' setting must be enabled.\n\n");
}
var ipRangeMiddleware = require('./lib/security').ipRangeRestrict(
this.get('allowed ip ranges'),
keystone.wrapHTMLError
);
this.pre('routes', ipRangeMiddleware);
}
// Pre-route middleware
this._pre.routes.forEach(function(fn) {
try {
app.use(fn);
}
catch(e) {
if (keystone.get('logger')) {
console.log('Invalid pre-route middleware provided');
}
throw e;
}
});
// Route requests
app.use(app.router);
// Headless mode means don't bind the Keystone routes
if (!this.get('headless')) {
this.routes(app);
}
// Handle redirects before 404s
if (Object.keys(this._redirects).length) {
app.use(function(req, res, next) {
if (keystone._redirects[req.path]) {
res.redirect(keystone._redirects[req.path]);
} else {
next();
}
});
}
// Handle 404 (no route matched) errors
var default404Handler = function(req, res, next) {
res.status(404).send(keystone.wrapHTMLError("Sorry, no page could be found at this address (404)"));
};
app.use(function(req, res, next) {
var err404 = keystone.get('404');
if (err404) {
try {
if ('function' === typeof err404) {
err404(req, res, next);
} else if ('string' === typeof err404) {
res.status(404).render(err404);
} else {
if (keystone.get('logger')) {
console.log(dashes + 'Error handling 404 (not found): Invalid type (' + (typeof err404) + ') for 404 setting.' + dashes);
}
default404Handler(req, res, next);
}
} catch(e) {
if (keystone.get('logger')) {
console.log(dashes + 'Error handling 404 (not found):');
console.log(e);
console.log(dashes);
}
default404Handler(req, res, next);
}
} else {
default404Handler(req, res, next);
}
});
// Handle other errors
var default500Handler = function(err, req, res, next) {
if (keystone.get('logger')) {
if (err instanceof Error) {
console.log((err.type ? err.type + ' ' : '') + 'Error thrown for request: ' + req.url);
} else {
console.log('Error thrown for request: ' + req.url);
}
console.log(err.stack || err);
}
var msg = '';
if (keystone.get('env') === 'development') {
if (err instanceof Error) {
if (err.type) {
msg += '<h2>' + err.type + '</h2>';
}
msg += utils.textToHTML(err.message);
} else if ('object' === typeof err) {
msg += '<code>' + JSON.stringify(err) + '</code>';
} else if (err) {
msg += err;
}
}
res.status(500).send(keystone.wrapHTMLError("Sorry, an error occurred loading the page (500)", msg));
};
app.use(function(err, req, res, next) {
var err500 = keystone.get('500');
if (err500) {
try {
if ('function' === typeof err500) {
err500(err, req, res, next);
} else if ('string' === typeof err500) {
res.locals.err = err;
res.status(500).render(err500);
} else {
if (keystone.get('logger')) {
console.log(dashes + 'Error handling 500 (error): Invalid type (' + (typeof err500) + ') for 500 setting.' + dashes);
}
default500Handler(err, req, res, next);
}
} catch(e) {
if (keystone.get('logger')) {
console.log(dashes + 'Error handling 500 (error):');
console.log(e);
console.log(dashes);
}
default500Handler(err, req, res, next);
}
} else {
default500Handler(err, req, res, next);
}
});
// Configure application routes
if ('function' === typeof this.get('routes')) {
this.get('routes')(app);
}
// Connect to database
var mongoConnectionOpen = false;
this.mongoose.connect(this.get('mongo'));
this.mongoose.connection.on('error', function(err) {
if (keystone.get('logger')) {
console.log('------------------------------------------------');
console.log('Mongo Error:\n');
console.log(err);
}
if (mongoConnectionOpen) {
throw new Error("Mongo Error");
} else {
throw new Error("KeystoneJS (" + keystone.get('name') + ") failed to start");
}
}).on('open', function() {
// app is mounted and db connection acquired, time to update and then call back
// Apply updates?
if (keystone.get('auto update')) {
keystone.applyUpdates(events.onMount);
} else {
events.onMount && events.onMount();
}
});
};
/**
* Configures and starts a Keystone app in encapsulated mode.
*
* Connects to the database, runs updates and listens for incoming requests.
*
* Events are fired during initialisation to allow customisation, including:
*
* - onMount
* - onStart
* - onHttpServerCreated
* - onHttpsServerCreated
*
* If the events argument is a function, it is assumed to be the started event.
*
*
* ####Options:
*
* Keystone supports the following options specifically for running in encapsulated mode:
*
* - name
* - port
* - views
* - view engine
* - compress
* - favico
* - less
* - static
* - headless
* - logger
* - cookie secret
* - session
* - 404
* - 500
* - routes
* - locals
* - auto update
* - ssl
* - sslport
* - sslkey
* - sslcert
*
*
* @api public
*/
Keystone.prototype.start = function(events) {
if ('function' === typeof events) {
events = { onStart: events };
}
if (!events) events = {};
if (!this.app) {
throw new Error("KeystoneJS Initialisaton Error:\n\napp must be initialised. Call keystone.init() or keystone.connect(new Express()) first.\n\n");
}
var keystone = this,
app = this.app;
//maintain passed in onMount binding but override to start http servers
//(call user-defined onMount first if present)
var onMount = events.onMount;
events.onMount = function() {
onMount && onMount();
mongoConnectionOpen = true;
var startupMessages = ['KeystoneJS Started:'],
waitForServers = 2;
// Logs the startup messages and calls the onStart method
var serverStarted = function() {
waitForServers--;
if (waitForServers) return;
if (keystone.get('logger')) {
console.log(dashes + startupMessages.join('\n') + dashes);
}
events.onStart && events.onStart();
};
// Creates the http server and listens to the specified port and host or listen option.
//
// For more information on how these options work, see
// http://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback
// and for history, see https://github.com/JedWatson/keystone/issues/154
keystone.httpServer = http.createServer(app);
events.onHttpServerCreated && events.onHttpServerCreated();
var host = keystone.get('host'),
port = keystone.get('port'),
listen = keystone.get('listen'),
ssl = keystone.get('ssl');
// start the http server unless we're in ssl-only mode
if (ssl != 'only') {
var httpStarted = function(msg) {
return function() {
startupMessages.push(msg);
serverStarted();
};
};
if (port || port === 0) {
app.set('port', port);
var httpReadyMsg = keystone.get('name') + ' is ready';
if (host) {
httpReadyMsg += ' on http://' + host;
if (port) {
httpReadyMsg += ':' + port;
}
// start listening on the specified host and port
keystone.httpServer.listen(port, host, httpStarted(httpReadyMsg));
} else {
if (port) {
httpReadyMsg += ' on port ' + port;
}
// start listening on any IPv4 address (INADDR_ANY) and the specified port
keystone.httpServer.listen(port, httpStarted(httpReadyMsg));
}
} else if (host) {
// start listening on a specific host address and default port 3000
app.set('port', 3000);
keystone.httpServer.listen(3000, host, httpStarted(keystone.get('name') + ' is ready on ' + host + ':3000'));
} else if (listen) {
// start listening to a unix socket
keystone.httpServer.listen(listen, httpStarted(keystone.get('name') + ' is ready' + (('string' === typeof listen) ? ' on ' + listen : '')));
} else {
// default: start listening on any IPv4 address (INADDR_ANY) and default port 3000
app.set('port', 3000);
keystone.httpServer.listen(3000, httpStarted(keystone.get('name') + ' is ready on default port 3000'));
}
} else {
waitForServers--;
}
// start the ssl server if configured
if (ssl) {
var sslOpts = {};
if (keystone.get('ssl cert') && fs.existsSync(keystone.getPath('ssl cert'))) {
sslOpts.cert = fs.readFileSync(keystone.getPath('ssl cert'));
}
if (keystone.get('ssl key') && fs.existsSync(keystone.getPath('ssl key'))) {
sslOpts.key = fs.readFileSync(keystone.getPath('ssl key'));
}
if (!sslOpts.key || !sslOpts.cert) {
if (ssl === 'only') {
console.log(keystone.get('name') + ' failed to start: invalid ssl configuration');
process.exit();
} else {
startupMessages.push('Warning: Invalid SSL Configuration');
serverStarted();
}
} else {
var httpsStarted = function(msg) {
return function() {
startupMessages.push(msg);
serverStarted();
};
};
keystone.httpsServer = https.createServer(sslOpts, app);
events.onHttpsServerCreated && events.onHttpsServerCreated();
var sslHost = keystone.get('ssl host') || host,
sslPort = keystone.get('ssl port') || 3001;
var httpsReadyMsg = (ssl === 'only') ? keystone.get('name') + ' (SSL) is ready on ' : 'SSL Server is ready on ';
if (sslHost) {
keystone.httpsServer.listen(sslPort, sslHost, httpsStarted(httpsReadyMsg + 'https://' + sslHost + ':' + sslPort));
} else {
var httpsPortMsg = (keystone.get('ssl port')) ? 'port: ' + keystone.get('ssl port') : 'default port 3001';
keystone.httpsServer.listen(sslPort, httpsStarted(httpsReadyMsg + httpsPortMsg));
}
}
} else {
waitForServers--;
}
process.on('uncaughtException', function(e) {
if (e.code === 'EADDRINUSE') {
console.log('------------------------------------------------\n' +
keystone.get('name') + ' failed to start: address already in use\n' +
'Please check you are not already running a server on the specified port.');
process.exit();
}/* else if (e.code === 'ECONNRESET') {
// Connection reset by peer, ignore it instead of exiting server with a throw.
// Disabled for release 0.2.16 while further research is being done.
console.log('Connection reset by peer');
console.log(e);
} */else {
console.log(e.stack || e);
process.exit(1);