loopback/common/models/role-mapping.js

99 lines
2.7 KiB
JavaScript
Raw Normal View History

2016-05-03 22:50:21 +00:00
// Copyright IBM Corp. 2014,2015. All Rights Reserved.
// Node module: loopback
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var loopback = require('../../lib/loopback');
var utils = require('../../lib/utils');
/**
* The `RoleMapping` model extends from the built in `loopback.Model` type.
*
* @property {String} id Generated ID.
* @property {String} name Name of the role.
* @property {String} Description Text description.
*
* @class RoleMapping
* @inherits {PersistedModel}
*/
module.exports = function(RoleMapping) {
2015-03-27 15:59:11 +00:00
// Principal types
RoleMapping.USER = 'USER';
RoleMapping.APP = RoleMapping.APPLICATION = 'APP';
RoleMapping.ROLE = 'ROLE';
RoleMapping.resolveRelatedModels = function() {
if (!this.userModel) {
var reg = this.registry;
this.roleModel = reg.getModelByType('Role');
this.userModel = reg.getModelByType('User');
this.applicationModel = reg.getModelByType('Application');
}
};
/**
* Get the application principal
* @callback {Function} callback
* @param {Error} err
* @param {Application} application
*/
2014-11-04 12:52:49 +00:00
RoleMapping.prototype.application = function(callback) {
callback = callback || utils.createPromiseCallback();
this.constructor.resolveRelatedModels();
if (this.principalType === RoleMapping.APPLICATION) {
var applicationModel = this.constructor.applicationModel;
applicationModel.findById(this.principalId, callback);
} else {
2014-11-04 12:52:49 +00:00
process.nextTick(function() {
callback(null, null);
});
}
return callback.promise;
};
/**
* Get the user principal
* @callback {Function} callback
* @param {Error} err
* @param {User} user
*/
2014-11-04 12:52:49 +00:00
RoleMapping.prototype.user = function(callback) {
callback = callback || utils.createPromiseCallback();
this.constructor.resolveRelatedModels();
if (this.principalType === RoleMapping.USER) {
var userModel = this.constructor.userModel;
userModel.findById(this.principalId, callback);
} else {
2014-11-04 12:52:49 +00:00
process.nextTick(function() {
callback(null, null);
});
}
return callback.promise;
};
/**
* Get the child role principal
* @callback {Function} callback
* @param {Error} err
* @param {User} childUser
*/
2014-11-04 12:52:49 +00:00
RoleMapping.prototype.childRole = function(callback) {
callback = callback || utils.createPromiseCallback();
this.constructor.resolveRelatedModels();
if (this.principalType === RoleMapping.ROLE) {
var roleModel = this.constructor.roleModel;
roleModel.findById(this.principalId, callback);
} else {
2014-11-04 12:52:49 +00:00
process.nextTick(function() {
callback(null, null);
});
}
return callback.promise;
};
};