-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
application.js
673 lines (584 loc) · 19 KB
/
application.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
// Copyright IBM Corp. 2013,2019. All Rights Reserved.
// Node module: loopback
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
/*!
* Module dependencies.
*/
'use strict';
const g = require('./globalize');
const DataSource = require('loopback-datasource-juggler').DataSource;
const Registry = require('./registry');
const assert = require('assert');
const fs = require('fs');
const extend = require('util')._extend;
const RemoteObjects = require('strong-remoting');
const classify = require('underscore.string/classify');
const camelize = require('underscore.string/camelize');
const path = require('path');
const util = require('util');
/**
* The `App` object represents a Loopback application.
*
* The App object extends [Express](http:https://expressjs.com/api.html#express) and
* supports Express middleware. See
* [Express documentation](http:https://expressjs.com/) for details.
*
* ```js
* var loopback = require('loopback');
* var app = loopback();
*
* app.get('/', function(req, res){
* res.send('hello world');
* });
*
* app.listen(3000);
* ```
*
* @class LoopBackApplication
* @header var app = loopback()
*/
function App() {
// this is a dummy placeholder for jsdox
}
/*!
* Export the app prototype.
*/
const app = module.exports = {};
/**
* Lazily load a set of [remote objects](http:https://apidocs.strongloop.com/strong-remoting/#remoteobjectsoptions).
*
* **NOTE:** Calling `app.remotes()` more than once returns only a single set of remote objects.
* @returns {RemoteObjects}
*/
app.remotes = function() {
if (this._remotes) {
return this._remotes;
} else {
let options = {};
if (this.get) {
options = this.get('remoting');
}
return (this._remotes = RemoteObjects.create(options));
}
};
/*!
* Remove a route by reference.
*/
app.disuse = function(route) {
if (this.stack) {
for (let i = 0; i < this.stack.length; i++) {
if (this.stack[i].route === route) {
this.stack.splice(i, 1);
}
}
}
};
/**
* Attach a model to the app. The `Model` will be available on the
* `app.models` object.
*
* Example - Attach an existing model:
```js
* var User = loopback.User;
* app.model(User);
*```
* Example - Attach an existing model, alter some aspects of the model:
* ```js
* var User = loopback.User;
* app.model(User, { dataSource: 'db' });
*```
*
* @param {Object} Model The model to attach.
* @options {Object} config The model's configuration.
* @property {String|DataSource} dataSource The `DataSource` to which to attach the model.
* @property {Boolean} [public] Whether the model should be exposed via REST API.
* @property {Object} [relations] Relations to add/update.
* @end
* @returns {ModelConstructor} the model class
*/
app.model = function(Model, config) {
let isPublic = true;
const registry = this.registry;
if (typeof Model === 'string') {
const msg = 'app.model(modelName, settings) is no longer supported. ' +
'Use app.registry.createModel(modelName, definition) and ' +
'app.model(ModelCtor, config) instead.';
throw new Error(msg);
}
if (arguments.length > 1) {
config = config || {};
configureModel(Model, config, this);
isPublic = config.public !== false;
} else {
assert(Model.prototype instanceof Model.registry.getModel('Model'),
Model.modelName + ' must be a descendant of loopback.Model');
}
const modelName = Model.modelName;
this.models[modelName] =
this.models[classify(modelName)] =
this.models[camelize(modelName)] = Model;
this.models().push(Model);
if (isPublic && Model.sharedClass) {
this.remotes().defineObjectType(Model.modelName, function(data) {
return new Model(data);
});
this.remotes().addClass(Model.sharedClass);
if (Model.settings.trackChanges && Model.Change) {
this.remotes().addClass(Model.Change.sharedClass);
}
clearHandlerCache(this);
this.emit('modelRemoted', Model.sharedClass);
}
const self = this;
Model.on('remoteMethodDisabled', function(model, methodName) {
clearHandlerCache(self);
self.emit('remoteMethodDisabled', model, methodName);
});
Model.on('remoteMethodAdded', function(model) {
clearHandlerCache(self);
self.emit('remoteMethodAdded', model);
});
Model.shared = isPublic;
Model.app = this;
Model.emit('attached', this);
return Model;
};
/**
* Remove all references to a previously registered Model.
*
* The method emits "modelDeleted" event as a counter-part to "modelRemoted"
* event.
*
* @param {String} modelName The name of the model to remove.
*/
app.deleteModelByName = function(modelName) {
const ModelCtor = this.models[modelName];
delete this.models[modelName];
delete this.models[classify(modelName)];
delete this.models[camelize(modelName)];
if (ModelCtor) {
ModelCtor.removeAllListeners();
const ix = this._models.indexOf(ModelCtor);
if (ix > -1) {
this._models.splice(ix, 1);
}
}
const remotes = this.remotes();
remotes.deleteClassByName(modelName);
remotes.deleteTypeByName(modelName);
if (ModelCtor && ModelCtor.dataSource) {
ModelCtor.dataSource.deleteModelByName(modelName);
} else {
this.registry.modelBuilder.deleteModelByName(modelName);
}
clearHandlerCache(this);
this.emit('modelDeleted', ModelCtor || modelName);
};
/**
* Get the models exported by the app. Returns only models defined using `app.model()`
*
* There are two ways to access models:
*
* 1. Call `app.models()` to get a list of all models.
*
* ```js
* var models = app.models();
*
* models.forEach(function(Model) {
* console.log(Model.modelName); // color
* });
* ```
*
* 2. Use `app.models` to access a model by name.
* `app.models` has properties for all defined models.
*
* The following example illustrates accessing the `Product` and `CustomerReceipt` models
* using the `models` object.
*
* ```js
* var loopback = require('loopback');
* var app = loopback();
* app.boot({
* dataSources: {
* db: {connector: 'memory'}
* }
* });
*
* var productModel = app.registry.createModel('product');
* app.model(productModel, {dataSource: 'db'});
* var customerReceiptModel = app.registry.createModel('customer-receipt');
* app.model(customerReceiptModel, {dataSource: 'db'});
*
* // available based on the given name
* var Product = app.models.Product;
*
* // also available as camelCase
* var product = app.models.product;
*
* // multi-word models are avaiable as pascal cased
* var CustomerReceipt = app.models.CustomerReceipt;
*
* // also available as camelCase
* var customerReceipt = app.models.customerReceipt;
* ```
*
* @returns {Array} Array of model classes.
*/
app.models = function() {
return this._models || (this._models = []);
};
/**
* Define a DataSource.
*
* @param {String} name The data source name
* @param {Object} config The data source config
*/
app.dataSource = function(name, config) {
try {
const ds = dataSourcesFromConfig(name, config, this.connectors, this.registry);
this.dataSources[name] =
this.dataSources[classify(name)] =
this.dataSources[camelize(name)] = ds;
ds.app = this;
return ds;
} catch (err) {
if (err.message) {
err.message = g.f('Cannot create data source %s: %s',
JSON.stringify(name), err.message);
}
throw err;
}
};
/**
* Register a connector.
*
* When a new data-source is being added via `app.dataSource`, the connector
* name is looked up in the registered connectors first.
*
* Connectors are required to be explicitly registered only for applications
* using browserify, because browserify does not support dynamic require,
* which is used by LoopBack to automatically load the connector module.
*
* @param {String} name Name of the connector, e.g. 'mysql'.
* @param {Object} connector Connector object as returned
* by `require('loopback-connector-{name}')`.
*/
app.connector = function(name, connector) {
this.connectors[name] =
this.connectors[classify(name)] =
this.connectors[camelize(name)] = connector;
};
/**
* Get all remote objects.
* @returns {Object} [Remote objects](http:https://apidocs.strongloop.com/strong-remoting/#remoteobjectsoptions).
*/
app.remoteObjects = function() {
const result = {};
this.remotes().classes().forEach(function(sharedClass) {
result[sharedClass.name] = sharedClass.ctor;
});
return result;
};
/*!
* Get a handler of the specified type from the handler cache.
* @triggers `mounted` events on shared class constructors (models)
*/
app.handler = function(type, options) {
const handlers = this._handlers || (this._handlers = {});
if (handlers[type]) {
return handlers[type];
}
const remotes = this.remotes();
const handler = this._handlers[type] = remotes.handler(type, options);
remotes.classes().forEach(function(sharedClass) {
sharedClass.ctor.emit('mounted', app, sharedClass, remotes);
});
return handler;
};
/**
* An object to store dataSource instances.
*/
app.dataSources = app.datasources = {};
/**
* Enable app wide authentication.
*/
app.enableAuth = function(options) {
const AUTH_MODELS = ['User', 'AccessToken', 'ACL', 'Role', 'RoleMapping'];
const remotes = this.remotes();
const app = this;
if (options && options.dataSource) {
const appModels = app.registry.modelBuilder.models;
AUTH_MODELS.forEach(function(m) {
const Model = app.registry.findModel(m);
if (!Model) {
throw new Error(
g.f('Authentication requires model %s to be defined.', m),
);
}
if (Model.dataSource || Model.app) return;
// Find descendants of Model that are attached,
// for example "Customer" extending "User" model
for (const name in appModels) {
const candidate = appModels[name];
const isSubclass = candidate.prototype instanceof Model;
const isAttached = !!candidate.dataSource || !!candidate.app;
if (isSubclass && isAttached) return;
}
app.model(Model, {
dataSource: options.dataSource,
public: m === 'User',
});
});
}
remotes.authorization = function(ctx, next) {
const method = ctx.method;
const req = ctx.req;
const Model = method.ctor;
const modelInstance = ctx.instance;
const modelId = modelInstance && modelInstance.id ||
// replacement for deprecated req.param()
(req.params && req.params.id !== undefined ? req.params.id :
req.body && req.body.id !== undefined ? req.body.id :
req.query && req.query.id !== undefined ? req.query.id :
undefined);
const modelName = Model.modelName;
const modelSettings = Model.settings || {};
let errStatusCode = modelSettings.aclErrorStatus || app.get('aclErrorStatus') || 401;
if (!req.accessToken) {
errStatusCode = 401;
}
if (Model.checkAccess) {
Model.checkAccess(
req.accessToken,
modelId,
method,
ctx,
function(err, allowed) {
if (err) {
console.log(err);
next(err);
} else if (allowed) {
next();
} else {
const messages = {
403: {
message: g.f('Access Denied'),
code: 'ACCESS_DENIED',
},
404: {
message: (g.f('could not find %s with id %s', modelName, modelId)),
code: 'MODEL_NOT_FOUND',
},
401: {
message: g.f('Authorization Required'),
code: 'AUTHORIZATION_REQUIRED',
},
};
const e = new Error(messages[errStatusCode].message || messages[403].message);
e.statusCode = errStatusCode;
e.code = messages[errStatusCode].code || messages[403].code;
next(e);
}
},
);
} else {
next();
}
};
this._verifyAuthModelRelations();
this.isAuthEnabled = true;
};
app._verifyAuthModelRelations = function() {
// Allow unit-tests (but also LoopBack users) to disable the warnings
if (this.get('_verifyAuthModelRelations') === false) return;
const AccessToken = this.registry.findModel('AccessToken');
const User = this.registry.findModel('User');
this.models().forEach(Model => {
if (Model === AccessToken || Model.prototype instanceof AccessToken) {
scheduleVerification(Model, verifyAccessTokenRelations);
}
if (Model === User || Model.prototype instanceof User) {
scheduleVerification(Model, verifyUserRelations);
}
});
function scheduleVerification(Model, verifyFn) {
if (Model.dataSource) {
verifyFn(Model);
} else {
Model.on('attached', () => verifyFn(Model));
}
}
function verifyAccessTokenRelations(Model) {
const belongsToUser = Model.relations && Model.relations.user;
if (belongsToUser) return;
const relationsConfig = Model.settings.relations || {};
const userName = (relationsConfig.user || {}).model;
if (userName) {
console.warn(
'The model %j configures "belongsTo User-like models" relation ' +
'with target model %j. However, the model %j is not attached to ' +
'the application and therefore cannot be used by this relation. ' +
'This typically happens when the application has a custom ' +
'custom User subclass, but does not fix AccessToken relations ' +
'to use this new model.\n' +
'Learn more at http:https://ibm.biz/setup-loopback-auth',
Model.modelName, userName, userName,
);
return;
}
console.warn(
'The model %j does not have "belongsTo User-like model" relation ' +
'configured.\n' +
'Learn more at http:https://ibm.biz/setup-loopback-auth',
Model.modelName,
);
}
function verifyUserRelations(Model) {
const hasManyTokens = Model.relations && Model.relations.accessTokens;
if (hasManyTokens) {
// display a temp warning message for users using multiple users config
if (hasManyTokens.polymorphic) {
console.warn(
'The app configuration follows the multiple user models setup ' +
'as described in http:https://ibm.biz/setup-loopback-auth',
'The built-in role resolver $owner is not currently compatible ' +
'with this configuration and should not be used in production.',
);
}
return;
}
const relationsConfig = Model.settings.relations || {};
const accessTokenName = (relationsConfig.accessTokens || {}).model;
if (accessTokenName) {
console.warn(
'The model %j configures "hasMany AccessToken-like models" relation ' +
'with target model %j. However, the model %j is not attached to ' +
'the application and therefore cannot be used by this relation. ' +
'This typically happens when the application has a custom ' +
'AccessToken subclass, but does not fix User relations to use this ' +
'new model.\n' +
'Learn more at http:https://ibm.biz/setup-loopback-auth',
Model.modelName, accessTokenName, accessTokenName,
);
return;
}
console.warn(
'The model %j does not have "hasMany AccessToken-like models" relation ' +
'configured.\n' +
'Learn more at http:https://ibm.biz/setup-loopback-auth',
Model.modelName,
);
}
};
app.boot = function(options) {
throw new Error(
g.f('{{`app.boot`}} was removed, use the new module {{loopback-boot}} instead'),
);
};
function dataSourcesFromConfig(name, config, connectorRegistry, registry) {
let connectorPath;
assert(typeof config === 'object',
'can not create data source without config object');
if (typeof config.connector === 'string') {
const connectorName = config.connector;
if (connectorRegistry[connectorName]) {
config.connector = connectorRegistry[connectorName];
} else {
connectorPath = path.join(__dirname, 'connectors', connectorName + '.js');
if (fs.existsSync(connectorPath)) {
config.connector = require(connectorPath);
}
}
if (config.connector && typeof config.connector === 'object' && !config.connector.name)
config.connector.name = connectorName;
}
return registry.createDataSource(name, config);
}
function configureModel(ModelCtor, config, app) {
assert(ModelCtor.prototype instanceof ModelCtor.registry.getModel('Model'),
ModelCtor.modelName + ' must be a descendant of loopback.Model');
let dataSource = config.dataSource;
if (dataSource) {
if (typeof dataSource === 'string') {
dataSource = app.dataSources[dataSource];
}
assert(
dataSource instanceof DataSource,
ModelCtor.modelName + ' is referencing a dataSource that does not exist: "' +
config.dataSource + '"',
);
}
config = extend({}, config);
config.dataSource = dataSource;
app.registry.configureModel(ModelCtor, config);
}
function clearHandlerCache(app) {
app._handlers = undefined;
}
/**
* Listen for connections and update the configured port.
*
* When there are no parameters or there is only one callback parameter,
* the server will listen on `app.get('host')` and `app.get('port')`.
*
* For example, to listen on host/port configured in app config:
* ```js
* app.listen();
* ```
*
* Otherwise all arguments are forwarded to `http.Server.listen`.
*
* For example, to listen on the specified port and all hosts, and ignore app config.
* ```js
* app.listen(80);
* ```
*
* The function also installs a `listening` callback that calls
* `app.set('port')` with the value returned by `server.address().port`.
* This way the port param contains always the real port number, even when
* listen was called with port number 0.
*
* @param {Function} [cb] If specified, the callback is added as a listener
* for the server's "listening" event.
* @returns {http.Server} A node `http.Server` with this application configured
* as the request handler.
*/
app.listen = function(cb) {
const self = this;
const server = require('http').createServer(this);
server.on('listening', function() {
self.set('port', this.address().port);
let listeningOnAll = false;
let host = self.get('host');
if (!host) {
listeningOnAll = true;
host = this.address().address;
self.set('host', host);
} else if (host === '0.0.0.0' || host === '::') {
listeningOnAll = true;
}
if (!self.get('url')) {
if (listeningOnAll) {
// We are replacing it with localhost to build a URL
// that can be copied and pasted into the browser.
host = 'localhost';
}
const url = 'http:https://' + host + ':' + self.get('port') + '/';
self.set('url', url);
}
});
const useAppConfig =
arguments.length === 0 ||
(arguments.length == 1 && typeof arguments[0] == 'function');
if (useAppConfig) {
let port = this.get('port');
// NOTE(bajtos) port:undefined no longer works on node@6,
// we must pass port:0 explicitly
if (port === undefined) port = 0;
server.listen(port, this.get('host'), cb);
} else {
server.listen.apply(server, arguments);
}
return server;
};