Auto-configure models required by `app.enableAuth`

Modify `app.enableAuth` to automaticaly setup all required models
that are not attached to the app nor a datasource.

Users wishing to use this option must provide the name of the
data-source to use for these models.

Example usage:

    var app = loopback();
    app.dataSource('db', { connector: 'memory' });
    app.enableAuth({ dataSource: 'db' });

    app.use(loopback.rest());
    app.listen(3000);
This commit is contained in:
Miroslav Bajtoš 2015-04-21 13:46:17 +02:00
parent 0ccc1e2b73
commit 3115e5055f
2 changed files with 56 additions and 1 deletions

View File

@ -291,10 +291,37 @@ app.dataSources = app.datasources = {};
* Enable app wide authentication.
*/
app.enableAuth = function() {
app.enableAuth = function(options) {
var AUTH_MODELS = ['User', 'AccessToken', 'ACL', 'Role', 'RoleMapping'];
var remotes = this.remotes();
var app = this;
if (options && options.dataSource) {
var appModels = app.registry.modelBuilder.models;
AUTH_MODELS.forEach(function(m) {
var Model = app.registry.findModel(m);
if (!Model) {
throw new Error(
'Authentication requires model ' + m + ' to be defined.');
}
if (m.dataSource || m.app) return;
for (var name in appModels) {
var candidate = appModels[name];
var isSubclass = candidate.prototype instanceof Model;
var isAttached = !!candidate.dataSource || !!candidate.app;
if (isSubclass && isAttached) return;
}
app.model(Model, {
dataSource: options.dataSource,
public: m === 'User'
});
});
}
remotes.authorization = function(ctx, next) {
var method = ctx.method;
var req = ctx.req;

View File

@ -796,6 +796,34 @@ describe('app', function() {
app.enableAuth();
expect(app.isAuthEnabled).to.equal(true);
});
it('auto-configures required models to provided dataSource', function() {
var AUTH_MODELS = ['User', 'ACL', 'AccessToken', 'Role', 'RoleMapping'];
var app = loopback({ localRegistry: true, loadBuiltinModels: true });
require('../lib/builtin-models')(app.registry);
var db = app.dataSource('db', { connector: 'memory' });
app.enableAuth({ dataSource: 'db' });
expect(Object.keys(app.models)).to.include.members(AUTH_MODELS);
AUTH_MODELS.forEach(function(m) {
var Model = app.models[m];
expect(Model.dataSource, m + '.dataSource').to.equal(db);
expect(Model.shared, m + '.shared').to.equal(m === 'User');
});
});
it('detects already configured subclass of a required model', function() {
var app = loopback({ localRegistry: true, loadBuiltinModels: true });
var db = app.dataSource('db', { connector: 'memory' });
var Customer = app.registry.createModel('Customer', {}, { base: 'User' });
app.model(Customer, { dataSource: 'db' });
app.enableAuth({ dataSource: 'db' });
expect(Object.keys(app.models)).to.not.include('User');
});
});
describe.onServer('app.get(\'/\', loopback.status())', function() {