common: coding style cleanup

This commit is contained in:
Miroslav Bajtoš 2014-11-04 13:52:49 +01:00
parent 2f1a1bcd7a
commit dc762d2514
12 changed files with 630 additions and 623 deletions

View File

@ -16,7 +16,7 @@
},
"validateJSDoc": {
"checkParamNames": false,
"checkRedundantParams": true,
"checkRedundantParams": false,
"requireParamTypes": true
}
}

View File

@ -5,8 +5,6 @@
"indent": 2,
"undef": true,
"quotmark": "single",
"maxlen": 150,
"trailing": true,
"newcap": true,
"nonew": true,
"sub": true,

View File

@ -33,7 +33,9 @@ module.exports = function(grunt) {
lib: {
src: ['lib/**/*.js']
},
// TODO(bajtos) - common/**/*.js
common: {
src: ['common/**/*.js']
},
// TODO tests don't pass yet
// test: {
// src: ['test/**/*.js']
@ -41,8 +43,9 @@ module.exports = function(grunt) {
},
jscs: {
gruntfile: 'Gruntfile.js',
lib: ['lib/**/*.js']
// TODO(bajtos) - common/**/*.js
lib: ['lib/**/*.js'],
common: ['common/**/*.js']
// TODO(bajtos) - test/**/*.js
},
watch: {
gruntfile: {

View File

@ -2,10 +2,10 @@
* Module Dependencies.
*/
var loopback = require('../../lib/loopback')
, assert = require('assert')
, uid = require('uid2')
, DEFAULT_TOKEN_LEN = 64;
var loopback = require('../../lib/loopback');
var assert = require('assert');
var uid = require('uid2');
var DEFAULT_TOKEN_LEN = 64;
/**
* Token based authentication and access control.
@ -57,7 +57,7 @@ module.exports = function(AccessToken) {
fn(null, guid);
}
});
}
};
/*!
* Hook to create accessToken id.
@ -75,7 +75,7 @@ module.exports = function(AccessToken) {
next();
}
});
}
};
/**
* Find a token for the given `ServerRequest`.
@ -115,7 +115,7 @@ module.exports = function(AccessToken) {
cb();
});
}
}
};
/**
* Validate the token.
@ -151,7 +151,7 @@ module.exports = function(AccessToken) {
} catch (e) {
cb(e);
}
}
};
function tokenIdForRequest(req, options) {
var params = options.params || [];

View File

@ -179,7 +179,7 @@ module.exports = function(ACL) {
ACL.prototype.score = function(req) {
return this.constructor.getMatchingScore(this, req);
}
};
/*!
* Resolve permission from the ACLs
@ -199,24 +199,26 @@ module.exports = function(ACL) {
var score = 0;
for (var i = 0; i < acls.length; i++) {
score = ACL.getMatchingScore(acls[i], req);
var candidate = acls[i];
score = ACL.getMatchingScore(candidate, req);
if (score < 0) {
// the highest scored ACL did not match
break;
}
if (!req.isWildcard()) {
// We should stop from the first match for non-wildcard
permission = acls[i].permission;
permission = candidate.permission;
break;
} else {
if (req.exactlyMatches(acls[i])) {
permission = acls[i].permission;
if (req.exactlyMatches(candidate)) {
permission = candidate.permission;
break;
}
// For wildcard match, find the strongest permission
if (AccessContext.permissionOrder[acls[i].permission]
> AccessContext.permissionOrder[permission]) {
permission = acls[i].permission;
var candidateOrder = AccessContext.permissionOrder[candidate.permission];
var permissionOrder = AccessContext.permissionOrder[permission];
if (candidateOrder > permissionOrder) {
permission = candidate.permission;
}
}
}
@ -246,8 +248,7 @@ module.exports = function(ACL) {
var staticACLs = [];
if (modelClass && modelClass.settings.acls) {
modelClass.settings.acls.forEach(function(acl) {
if (!acl.property || acl.property === ACL.ALL
|| property === acl.property) {
if (!acl.property || acl.property === ACL.ALL || property === acl.property) {
staticACLs.push(new ACL({
model: model,
property: acl.property || ACL.ALL,
@ -259,11 +260,15 @@ module.exports = function(ACL) {
}
});
}
var prop = modelClass &&
(modelClass.definition.properties[property] // regular property
|| (modelClass._scopeMeta && modelClass._scopeMeta[property]) // relation/scope
|| modelClass[property] // static method
|| modelClass.prototype[property]); // prototype method
var prop = modelClass && (
// regular property
modelClass.definition.properties[property] ||
// relation/scope
(modelClass._scopeMeta && modelClass._scopeMeta[property]) ||
// static method
modelClass[property] ||
// prototype method
modelClass.prototype[property]);
if (prop && prop.acls) {
prop.acls.forEach(function(acl) {
staticACLs.push(new ACL({
@ -311,7 +316,7 @@ module.exports = function(ACL) {
debug('Permission denied by statically resolved permission');
debug(' Resolved Permission: %j', resolved);
process.nextTick(function() {
callback && callback(null, resolved);
if (callback) callback(null, resolved);
});
return;
}
@ -321,7 +326,7 @@ module.exports = function(ACL) {
model: model, property: propertyQuery, accessType: accessTypeQuery}},
function(err, dynACLs) {
if (err) {
callback && callback(err);
if (callback) callback(err);
return;
}
acls = acls.concat(dynACLs);
@ -330,7 +335,7 @@ module.exports = function(ACL) {
var modelClass = loopback.findModel(model);
resolved.permission = (modelClass && modelClass.settings.defaultPermission) || ACL.ALLOW;
}
callback && callback(null, resolved);
if (callback) callback(null, resolved);
});
};
@ -344,7 +349,7 @@ module.exports = function(ACL) {
debug('accessType %s', this.accessType);
debug('permission %s', this.permission);
}
}
};
/**
* Check if the request has the permission to access.
@ -381,7 +386,7 @@ module.exports = function(ACL) {
this.find({where: {model: model.modelName, property: propertyQuery,
accessType: accessTypeQuery}}, function(err, acls) {
if (err) {
callback && callback(err);
if (callback) callback(err);
return;
}
var inRoleTasks = [];
@ -392,8 +397,9 @@ module.exports = function(ACL) {
// Check exact matches
for (var i = 0; i < context.principals.length; i++) {
var p = context.principals[i];
if (p.type === acl.principalType
&& String(p.id) === String(acl.principalId)) {
var typeMatch = p.type === acl.principalType;
var idMatch = String(p.id) === String(acl.principalId);
if (typeMatch && idMatch) {
effectiveACLs.push(acl);
return;
}
@ -415,7 +421,7 @@ module.exports = function(ACL) {
async.parallel(inRoleTasks, function(err, results) {
if (err) {
callback && callback(err, null);
if (callback) callback(err, null);
return;
}
var resolved = self.resolvePermission(effectiveACLs, req);
@ -424,7 +430,7 @@ module.exports = function(ACL) {
}
debug('---Resolved---');
resolved.debug();
callback && callback(null, resolved);
if (callback) callback(null, resolved);
});
});
};
@ -452,11 +458,10 @@ module.exports = function(ACL) {
this.checkAccessForContext(context, function(err, access) {
if (err) {
callback && callback(err);
if (callback) callback(err);
return;
}
callback && callback(null, access.permission !== ACL.DENY);
if (callback) callback(null, access.permission !== ACL.DENY);
});
};
}
};

View File

@ -141,7 +141,7 @@ module.exports = function(Application) {
Application.resetKeys = function(appId, cb) {
this.findById(appId, function(err, app) {
if (err) {
cb && cb(err, app);
if (cb) cb(err, app);
return;
}
app.resetKeys(cb);
@ -166,7 +166,7 @@ module.exports = function(Application) {
Application.authenticate = function(appId, key, cb) {
this.findById(appId, function(err, app) {
if (err || !app) {
cb && cb(err, null);
if (cb) cb(err, null);
return;
}
var result = null;
@ -180,7 +180,7 @@ module.exports = function(Application) {
break;
}
}
cb && cb(null, result);
if (cb) cb(null, result);
});
};
};

View File

@ -2,14 +2,13 @@
* Module Dependencies.
*/
var PersistedModel = require('../../lib/loopback').PersistedModel
, loopback = require('../../lib/loopback')
, crypto = require('crypto')
, CJSON = {stringify: require('canonical-json')}
, async = require('async')
, assert = require('assert')
, debug = require('debug')('loopback:change');
var PersistedModel = require('../../lib/loopback').PersistedModel;
var loopback = require('../../lib/loopback');
var crypto = require('crypto');
var CJSON = {stringify: require('canonical-json')};
var async = require('async');
var assert = require('assert');
var debug = require('debug')('loopback:change');
/**
* Change list entry.
@ -55,8 +54,8 @@ module.exports = function(Change) {
if (!hasModel) return null;
return Change.idForModel(this.modelName, this.modelId);
}
}
};
};
Change.setup();
/**
@ -82,7 +81,7 @@ module.exports = function(Change) {
});
});
async.parallel(tasks, callback);
}
};
/**
* Get an identifier for a given model.
@ -94,7 +93,7 @@ module.exports = function(Change) {
Change.idForModel = function(modelName, modelId) {
return this.hash([modelName, modelId].join('-'));
}
};
/**
* Find or create a change for the given model.
@ -126,7 +125,7 @@ module.exports = function(Change) {
ch.save(callback);
}
});
}
};
/**
* Update (or create) the change with the current revision.
@ -148,7 +147,7 @@ module.exports = function(Change) {
cb = cb || function(err) {
if (err) throw new Error(err);
}
};
async.parallel(tasks, function(err) {
if (err) return cb(err);
@ -194,7 +193,7 @@ module.exports = function(Change) {
cb();
});
}
}
};
/**
* Get a change's current revision based on current data.
@ -214,7 +213,7 @@ module.exports = function(Change) {
cb(null, null);
}
});
}
};
/**
* Create a hash of the given `string` with the `options.hashAlgorithm`.
@ -229,7 +228,7 @@ module.exports = function(Change) {
.createHash(Change.settings.hashAlgorithm || 'sha1')
.update(str)
.digest('hex');
}
};
/**
* Get the revision string for the given object
@ -239,7 +238,7 @@ module.exports = function(Change) {
Change.revisionForInst = function(inst) {
return this.hash(CJSON.stringify(inst));
}
};
/**
* Get a change's type. Returns one of:
@ -263,7 +262,7 @@ module.exports = function(Change) {
return Change.DELETE;
}
return Change.UNKNOWN;
}
};
/**
* Compare two changes.
@ -276,7 +275,7 @@ module.exports = function(Change) {
var thisRev = this.rev || null;
var thatRev = change.rev || null;
return thisRev === thatRev;
}
};
/**
* Does this change conflict with the given change.
@ -290,7 +289,7 @@ module.exports = function(Change) {
if (Change.bothDeleted(this, change)) return false;
if (this.isBasedOn(change)) return false;
return true;
}
};
/**
* Are both changes deletes?
@ -300,9 +299,9 @@ module.exports = function(Change) {
*/
Change.bothDeleted = function(a, b) {
return a.type() === Change.DELETE
&& b.type() === Change.DELETE;
}
return a.type() === Change.DELETE &&
b.type() === Change.DELETE;
};
/**
* Determine if the change is based on the given change.
@ -312,7 +311,7 @@ module.exports = function(Change) {
Change.prototype.isBasedOn = function(change) {
return this.prev === change.rev;
}
};
/**
* Determine the differences for a given model since a given checkpoint.
@ -393,11 +392,11 @@ module.exports = function(Change) {
conflicts: conflicts
});
});
}
};
/**
* Correct all change list entries.
* @param {Function} callback
* @param {Function} cb
*/
Change.rectifyAll = function(cb) {
@ -411,7 +410,7 @@ module.exports = function(Change) {
change.rectify();
});
});
}
};
/**
* Get the checkpoint model.
@ -426,13 +425,13 @@ module.exports = function(Change) {
+ ' is not attached to a dataSource');
checkpointModel.attachTo(this.dataSource);
return checkpointModel;
}
};
Change.handleError = function(err) {
if (!this.settings.ignoreErrors) {
throw err;
}
}
};
Change.prototype.debug = function() {
if (debug.enabled) {
@ -445,7 +444,7 @@ module.exports = function(Change) {
debug('\tmodelId', this.modelId);
debug('\ttype', this.type());
}
}
};
/**
* Get the `Model` class for `change.modelName`.
@ -454,7 +453,7 @@ module.exports = function(Change) {
Change.prototype.getModelCtor = function() {
return this.constructor.settings.trackModel;
}
};
Change.prototype.getModelId = function() {
// TODO(ritch) get rid of the need to create an instance
@ -463,13 +462,13 @@ module.exports = function(Change) {
var m = new Model();
m.setId(id);
return m.getId();
}
};
Change.prototype.getModel = function(callback) {
var Model = this.constructor.settings.trackModel;
var id = this.getModelId();
Model.findById(id, callback);
}
};
/**
* When two changes conflict a conflict is created.
@ -533,7 +532,7 @@ module.exports = function(Change) {
if (err) return cb(err);
cb(null, source, target);
}
}
};
/**
* Get the conflicting changes.
@ -578,7 +577,7 @@ module.exports = function(Change) {
if (err) return cb(err);
cb(null, sourceChange, targetChange);
}
}
};
/**
* Resolve the conflict.
@ -594,7 +593,7 @@ module.exports = function(Change) {
sourceChange.prev = targetChange.rev;
sourceChange.save(cb);
});
}
};
/**
* Determine the conflict type.
@ -624,5 +623,5 @@ module.exports = function(Change) {
}
return cb(null, Change.UNKNOWN);
});
}
};
};

View File

@ -47,7 +47,7 @@ module.exports = function(Checkpoint) {
});
}
});
}
};
Checkpoint.beforeSave = function(next, model) {
if (!model.getId() && model.seq === undefined) {
@ -59,5 +59,5 @@ module.exports = function(Checkpoint) {
} else {
next();
}
}
};
};

View File

@ -23,14 +23,14 @@ module.exports = function(RoleMapping) {
* @param {Error} err
* @param {Application} application
*/
RoleMapping.prototype.application = function (callback) {
RoleMapping.prototype.application = function(callback) {
if (this.principalType === RoleMapping.APPLICATION) {
var applicationModel = this.constructor.Application
|| loopback.getModelByType(loopback.Application);
var applicationModel = this.constructor.Application ||
loopback.getModelByType(loopback.Application);
applicationModel.findById(this.principalId, callback);
} else {
process.nextTick(function () {
callback && callback(null, null);
process.nextTick(function() {
if (callback) callback(null, null);
});
}
};
@ -41,14 +41,14 @@ module.exports = function(RoleMapping) {
* @param {Error} err
* @param {User} user
*/
RoleMapping.prototype.user = function (callback) {
RoleMapping.prototype.user = function(callback) {
if (this.principalType === RoleMapping.USER) {
var userModel = this.constructor.User
|| loopback.getModelByType(loopback.User);
var userModel = this.constructor.User ||
loopback.getModelByType(loopback.User);
userModel.findById(this.principalId, callback);
} else {
process.nextTick(function () {
callback && callback(null, null);
process.nextTick(function() {
if (callback) callback(null, null);
});
}
};
@ -59,14 +59,14 @@ module.exports = function(RoleMapping) {
* @param {Error} err
* @param {User} childUser
*/
RoleMapping.prototype.childRole = function (callback) {
RoleMapping.prototype.childRole = function(callback) {
if (this.principalType === RoleMapping.ROLE) {
var roleModel = this.constructor.Role ||
loopback.getModelByType(loopback.Role);
roleModel.findById(this.principalId, callback);
} else {
process.nextTick(function () {
callback && callback(null, null);
process.nextTick(function() {
if (callback) callback(null, null);
});
}
};

View File

@ -33,7 +33,7 @@ module.exports = function(Role) {
roleMappingModel.find({where: {roleId: this.id,
principalType: RoleMapping.USER}}, function(err, mappings) {
if (err) {
callback && callback(err);
if (callback) callback(err);
return;
}
return mappings.map(function(m) {
@ -46,7 +46,7 @@ module.exports = function(Role) {
roleMappingModel.find({where: {roleId: this.id,
principalType: RoleMapping.APPLICATION}}, function(err, mappings) {
if (err) {
callback && callback(err);
if (callback) callback(err);
return;
}
return mappings.map(function(m) {
@ -59,7 +59,7 @@ module.exports = function(Role) {
roleMappingModel.find({where: {roleId: this.id,
principalType: RoleMapping.ROLE}}, function(err, mappings) {
if (err) {
callback && callback(err);
if (callback) callback(err);
return;
}
return mappings.map(function(m) {
@ -72,10 +72,10 @@ module.exports = function(Role) {
// Special roles
Role.OWNER = '$owner'; // owner of the object
Role.RELATED = "$related"; // any User with a relationship to the object
Role.AUTHENTICATED = "$authenticated"; // authenticated user
Role.UNAUTHENTICATED = "$unauthenticated"; // authenticated user
Role.EVERYONE = "$everyone"; // everyone
Role.RELATED = '$related'; // any User with a relationship to the object
Role.AUTHENTICATED = '$authenticated'; // authenticated user
Role.UNAUTHENTICATED = '$unauthenticated'; // authenticated user
Role.EVERYONE = '$everyone'; // everyone
/**
* Add custom handler for roles.
@ -93,7 +93,7 @@ module.exports = function(Role) {
Role.registerResolver(Role.OWNER, function(role, context, callback) {
if (!context || !context.model || !context.modelId) {
process.nextTick(function() {
callback && callback(null, false);
if (callback) callback(null, false);
});
return;
}
@ -152,13 +152,13 @@ module.exports = function(Role) {
modelClass.findById(modelId, function(err, inst) {
if (err || !inst) {
debug('Model not found for id %j', modelId);
callback && callback(err, false);
if (callback) callback(err, false);
return;
}
debug('Model found: %j', inst);
var ownerId = inst.userId || inst.owner;
if (ownerId) {
callback && callback(null, matches(ownerId, userId));
if (callback) callback(null, matches(ownerId, userId));
return;
} else {
// Try to follow belongsTo
@ -166,19 +166,21 @@ module.exports = function(Role) {
var rel = modelClass.relations[r];
if (rel.type === 'belongsTo' && isUserClass(rel.modelTo)) {
debug('Checking relation %s to %s: %j', r, rel.modelTo.modelName, rel);
inst[r](function(err, user) {
if (!err && user) {
debug('User found: %j', user.id);
callback && callback(null, matches(user.id, userId));
} else {
callback && callback(err, false);
}
});
inst[r](processRelatedUser);
return;
}
}
debug('No matching belongsTo relation found for model %j and user: %j', modelId, userId);
callback && callback(null, false);
if (callback) callback(null, false);
}
function processRelatedUser(err, user) {
if (!err && user) {
debug('User found: %j', user.id);
if (callback) callback(null, matches(user.id, userId));
} else {
if (callback) callback(err, false);
}
}
});
};
@ -186,7 +188,7 @@ module.exports = function(Role) {
Role.registerResolver(Role.AUTHENTICATED, function(role, context, callback) {
if (!context) {
process.nextTick(function() {
callback && callback(null, false);
if (callback) callback(null, false);
});
return;
}
@ -202,19 +204,19 @@ module.exports = function(Role) {
*/
Role.isAuthenticated = function isAuthenticated(context, callback) {
process.nextTick(function() {
callback && callback(null, context.isAuthenticated());
if (callback) callback(null, context.isAuthenticated());
});
};
Role.registerResolver(Role.UNAUTHENTICATED, function(role, context, callback) {
process.nextTick(function() {
callback && callback(null, !context || !context.isAuthenticated());
if (callback) callback(null, !context || !context.isAuthenticated());
});
});
Role.registerResolver(Role.EVERYONE, function(role, context, callback) {
process.nextTick(function() {
callback && callback(null, true); // Always true
if (callback) callback(null, true); // Always true
});
});
@ -245,7 +247,7 @@ module.exports = function(Role) {
if (context.principals.length === 0) {
debug('isInRole() returns: false');
process.nextTick(function() {
callback && callback(null, false);
if (callback) callback(null, false);
});
return;
}
@ -262,7 +264,7 @@ module.exports = function(Role) {
if (inRole) {
debug('isInRole() returns: %j', inRole);
process.nextTick(function() {
callback && callback(null, true);
if (callback) callback(null, true);
});
return;
}
@ -270,11 +272,11 @@ module.exports = function(Role) {
var roleMappingModel = this.RoleMapping || loopback.getModelByType(RoleMapping);
this.findOne({where: {name: role}}, function(err, result) {
if (err) {
callback && callback(err);
if (callback) callback(err);
return;
}
if (!result) {
callback && callback(null, false);
if (callback) callback(null, false);
return;
}
debug('Role found: %j', result);
@ -303,7 +305,7 @@ module.exports = function(Role) {
}
}, function(inRole) {
debug('isInRole() returns: %j', inRole);
callback && callback(null, inRole);
if (callback) callback(null, inRole);
});
});
@ -315,8 +317,8 @@ module.exports = function(Role) {
* @param {Function} callback
*
* @callback {Function} callback
* @param err
* @param {String[]} An array of role ids
* @param {Error=} err
* @param {String[]} roles An array of role ids
*/
Role.getRoles = function(context, callback) {
if (!(context instanceof AccessContext)) {
@ -354,8 +356,8 @@ module.exports = function(Role) {
// Check against the role mappings
var principalType = p.type || undefined;
var principalId = p.id == null ? undefined : p.id;
if(typeof principalId !== 'string' && principalId != null) {
if (typeof principalId !== 'string' && principalId != null) {
principalId = principalId.toString();
}
@ -371,13 +373,13 @@ module.exports = function(Role) {
principalId: principalId}}, function(err, mappings) {
debug('Role mappings found: %s %j', err, mappings);
if (err) {
done && done(err);
if (done) done(err);
return;
}
mappings.forEach(function(m) {
addRole(m.roleId);
});
done && done();
if (done) done();
});
});
}
@ -385,7 +387,7 @@ module.exports = function(Role) {
async.parallel(inRoleTasks, function(err, results) {
debug('getRoles() returns: %j %j', err, roles);
callback && callback(err, roles);
if (callback) callback(err, roles);
});
};
};

View File

@ -23,14 +23,14 @@ module.exports = function(Scope) {
* @param {String|Error} err The error object
* @param {AccessRequest} result The access permission
*/
Scope.checkPermission = function (scope, model, property, accessType, callback) {
Scope.checkPermission = function(scope, model, property, accessType, callback) {
var ACL = loopback.ACL;
assert(ACL,
'ACL model must be defined before Scope.checkPermission is called');
this.findOne({where: {name: scope}}, function (err, scope) {
this.findOne({where: {name: scope}}, function(err, scope) {
if (err) {
callback && callback(err);
if (callback) callback(err);
} else {
var aclModel = loopback.getModelByType(ACL);
aclModel.checkPermission(ACL.SCOPE, scope.id, model, property, accessType, callback);

File diff suppressed because it is too large Load Diff