Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

rhases-nodejs-commons

Package Overview
Dependencies
Maintainers
3
Versions
45
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

rhases-nodejs-commons - npm Package Compare versions

Comparing version 0.3.5 to 1.0.1

14

CHANGELOG.md

@@ -5,16 +5,6 @@ # Change Log

<a name="0.2.25"></a>
## [0.2.25](https://github.com/rhases/rhases-nodejs-commons/compare/v0.2.24...v0.2.25) (2017-11-20)
<a name="1.0.1"></a>
## [1.0.1](https://github.com/rhases/rhases-nodejs-commons/compare/v0.2.21...v1.0.1) (2018-08-23)
<a name="0.2.24"></a>
## [0.2.24](https://github.com/rhases/rhases-nodejs-commons/compare/v0.2.23...v0.2.24) (2017-10-17)
<a name="0.2.23"></a>
## [0.2.23](https://github.com/rhases/rhases-nodejs-commons/compare/v0.2.21...v0.2.23) (2017-10-10)
### Bug Fixes

@@ -21,0 +11,0 @@

18

dist/crud/access-control-base.controller.d.ts

@@ -9,12 +9,12 @@ import { Promise } from 'q';

constructor(model: Model<Document>, grants: any);
create(req: any, res: Response): any;
find(req: any, res: Response, exQueryBuilder?: (DocumentQuery) => DocumentQuery<any, any>): any;
findById(req: any, res: Response, exQueryBuilder?: (DocumentQuery) => DocumentQuery<any, any>): any;
create(req: any, res: Response): void;
find(req: any, res: Response, exQueryBuilder?: (DocumentQuery: any) => DocumentQuery<any, any>): void;
findById(req: any, res: Response, exQueryBuilder?: (DocumentQuery: any) => DocumentQuery<any, any>): void;
restrictedQueryBuilderFactory(grant: any, user: any, exQueryBuilder?: any): () => (query: any) => any;
update(req: any, res: Response): any;
patch(req: any, res: Response): any;
remove(req: any, res: Response): any;
private setOwner(grant, user);
private findBydId(id, user, grant);
private entityFromBody(req);
update(req: any, res: Response): void;
patch(req: any, res: Response): void;
remove(req: any, res: Response): void;
private setOwner;
private findBydId;
private entityFromBody;
}

@@ -22,3 +22,3 @@ "use strict";

var self = this;
return controller_utils_1.baseHandle(req, res, self.promisedAc, 'create', function (grant, user) {
controller_utils_1.baseHandle(req, res, self.promisedAc, 'create', function (grant, user) {
return Q.when()

@@ -32,3 +32,3 @@ .then(self.entityFromBody(req))

var self = this;
return controller_utils_1.baseHandle(req, res, self.promisedAc, 'read', function (grant, user) {
controller_utils_1.baseHandle(req, res, self.promisedAc, 'read', function (grant, user) {
return Q.when()

@@ -42,3 +42,3 @@ .then(self.restrictedQueryBuilderFactory(grant, user, exQueryBuilder))

var self = this;
return controller_utils_1.baseHandle(req, res, self.promisedAc, 'read', function (grant, user) {
controller_utils_1.baseHandle(req, res, self.promisedAc, 'read', function (grant, user) {
return Q.when()

@@ -53,7 +53,5 @@ .then(self.restrictedQueryBuilderFactory(grant, user, exQueryBuilder))

var restrictedQueryBuilder = function (query) {
var organizationCodes = user.roles
.filter(function (role) { return role.indexOf('$organization') == 0; })
.map(function (role) { return role.replace('$organization:', '').replace(/:.*$/, ''); });
var organizationCode = user.organization && user.organization.ref ? user.organization.ref.code : undefined;
return functions_utils_1.now(query)
.then(promise_grants_utils_1.ifGrantedForOwn(grant, base_query_builder_1.restrictByOwner(grant.ownerTypes, user._id, organizationCodes)))
.then(promise_grants_utils_1.ifGrantedForOwn(grant, base_query_builder_1.restrictByOwner(grant.ownerTypes, user._id, organizationCode)))
.then(promise_grants_utils_1.ifDefined(exQueryBuilder))

@@ -67,3 +65,3 @@ .value();

var self = this;
return controller_utils_1.baseHandle(req, res, self.promisedAc, 'update', function (grant, user) {
controller_utils_1.baseHandle(req, res, self.promisedAc, 'update', function (grant, user) {
return Q.when()

@@ -78,3 +76,3 @@ .then(self.restrictedQueryBuilderFactory(grant, user))

var self = this;
return controller_utils_1.baseHandle(req, res, self.promisedAc, 'update', function (grant, user) {
controller_utils_1.baseHandle(req, res, self.promisedAc, 'update', function (grant, user) {
return Q.when()

@@ -89,3 +87,3 @@ .then(self.restrictedQueryBuilderFactory(grant, user))

var self = this;
return controller_utils_1.baseHandle(req, res, self.promisedAc, 'delete', function (grant, user) {
controller_utils_1.baseHandle(req, res, self.promisedAc, 'delete', function (grant, user) {
return Q.when()

@@ -105,2 +103,3 @@ .then(self.restrictedQueryBuilderFactory(grant, user))

.then(promise_grants_utils_1.ifGrantedForUser(grant, entity_utils_1.setUserOwner(user)))
.then(promise_grants_utils_1.ifGrantedForOrganization(grant, entity_utils_1.setOrganizationOwner(user)))
.value();

@@ -107,0 +106,0 @@ };

import { CrudAccessControl } from './access-control.authorization';
import { Promise } from 'q';
export declare function crudAccessControlWithOrgRolesFactory(resource: any, grants: any): Promise<CrudAccessControl>;

@@ -14,9 +14,5 @@ 'use strict';

logger_1.default.warn(thisGrants[0].resource);
return Q.when(thisGrants)
return queryAllOrgs()
.then(expandGrantsListRules(thisGrants))
.then(instantiateCrudAccessControl(resource));
/*
return queryAllOrgs()
.then(expandGrantsListRules(thisGrants))
.then(instantiateCrudAccessControl(resource))
*/
}

@@ -34,24 +30,25 @@ exports.crudAccessControlWithOrgRolesFactory = crudAccessControlWithOrgRolesFactory;

}
// function expandGrantsListRules(grants){
// return function(organizations:Array<any> ){
// l.trace('expanding grants');
// return grants.reduce(function(acc, grant){
// if( _.startsWith(grant.role, '$organization') ){
// l.trace('grant to be expanded');
// var orgRole = grant.role.slice('$organization:'.length);
// var grunts = organizations.map(function(organization){
// var newGrant = _.clone(grant);
// newGrant.role = `${organization.code}:${orgRole}`;
// l.trace(`grants added with role ${newGrant.role}`);
// return newGrant;
// })
// acc = _.concat(acc, grunts)
// }else {
// l.trace(`grants added as is '${grant.role}'`);
// acc.push(grant);
// }
// return acc;
// }, [])
// }
// }
function expandGrantsListRules(grants) {
return function (organizations) {
logger_1.default.trace('expanding grants');
return grants.reduce(function (acc, grant) {
if (_.startsWith(grant.role, '$organization')) {
logger_1.default.trace('grant to be expanded');
var orgRole = grant.role.slice('$organizationa'.length);
var grunts = organizations.map(function (organization) {
var newGrant = _.clone(grant);
newGrant.role = organization.code + ":" + orgRole;
logger_1.default.trace("grants added with role " + newGrant.role);
return newGrant;
});
acc = _.concat(acc, grunts);
}
else {
logger_1.default.trace("grants added as is '" + grant.role + "'");
acc.push(grant);
}
return acc;
}, []);
};
}
function instantiateCrudAccessControl(resource) {

@@ -58,0 +55,0 @@ return function (grants) {

@@ -9,3 +9,3 @@ "use strict";

var promisedAcessControl;
var newVideo, myVideo, videoFromThirdPary, adminUser, normalUser, organizationManager, organizationOtherRole, organizationMember, guestUser;
var newVideo, myVideo, videoFromThirdPary, adminUser, normalUser, organizationManager, organizationMember, guestUser;
var queryMock;

@@ -21,4 +21,4 @@ promisedAcessControl = access_control_with_organizations_authorization_1.crudAccessControlWithOrgRolesFactory('video', [

{ role: '$organization:member', resource: 'video', action: 'update:own', attributes: ['*'] },
{ role: '$organization:manager', resource: 'video', action: 'read:any', attributes: ['*'] },
{ role: '$organization:manager', resource: 'video', action: 'create:own', attributes: ['*'] },
{ role: '$organization:manager', resource: 'video', action: 'read:own', attributes: ['*'] },
{ role: '$organization:manager', resource: 'video', action: 'update:own', attributes: ['*'] },

@@ -35,10 +35,2 @@ { role: '$organization:manager', resource: 'video', action: 'delete:own', attributes: ['*'] }

};
organizationOtherRole = {
_id: '0010',
roles: ['user'],
organization: {
ref: { code: 'vert' },
role: 'other1'
}
};
organizationMember = {

@@ -56,13 +48,2 @@ _id: '002',

};
it('should organization manager be grant read any', function () {
return promisedAcessControl
.then(function (accessControll) {
return accessControll.check(organizationManager, 'read');
})
.then(function (grant) {
logger_1.default.trace('asserting permission attrs');
chai_1.expect(grant.granted).to.equal(true);
chai_1.expect(grant.type).to.equal('any');
});
});
it('should organization manager be grant create access', function () {

@@ -69,0 +50,0 @@ return promisedAcessControl

@@ -8,5 +8,4 @@ import { AccessControl, Permission } from 'accesscontrol';

check(user: any, op: string): Grant;
private doCheck(_ac, roles, op, type, resource);
private doCheck;
private grantOwn;
filteredRoles(_ac: any, roles: any): any;
getOrgRoles(user: any): any[];

@@ -13,0 +12,0 @@ }

@@ -15,16 +15,8 @@ 'use strict';

//check for `any` clearence: the user has accesss to any document in the target collection
logger_1.default.trace("all roles of user: " + user.roles);
var grant;
var roles = this.filteredRoles(_ac, user.roles);
logger_1.default.trace("filtered user roles: " + roles);
var orgRoles = this.getOrgRoles(user);
logger_1.default.trace("org roles: " + orgRoles);
orgRoles = this.filteredRoles(_ac, orgRoles);
logger_1.default.trace("filtered org roles: " + orgRoles);
logger_1.default.trace("check can " + roles + " " + op + "Any for " + this.resource);
var anyRoles = roles.concat(orgRoles);
var anyPermission = this.doCheck(_ac, anyRoles, op, 'Any', this.resource);
logger_1.default.trace("check can " + user.roles + " " + op + "Any for " + this.resource);
var anyPermission = this.doCheck(_ac, user.roles, op, 'Any', this.resource);
if (anyPermission.granted) {
grant = new Grant(anyPermission, 'any');
grant.addVerifiedRoles(anyRoles);
grant.addVerifiedRoles(user.roles);
}

@@ -35,5 +27,5 @@ else {

///check for `own` clearence for 'user'
logger_1.default.trace("check can '" + roles + "' " + op + "Own for " + this.resource);
var userOwnPermission = this.doCheck(_ac, roles, op, 'Own', this.resource);
ownGrant.addVerifiedRoles(roles);
logger_1.default.trace("check can " + user.roles + " " + op + "Own for " + this.resource);
var userOwnPermission = this.doCheck(_ac, user.roles, op, 'Own', this.resource);
ownGrant.addVerifiedRoles(user.roles);
//check for `organization:own` clearence

@@ -44,3 +36,4 @@ if (userOwnPermission.granted) {

//check for 'own' clearence for 'organization'
logger_1.default.trace("check can '" + orgRoles + "' " + op + "Own for " + this.resource);
var orgRoles = this.getOrgRoles(user);
logger_1.default.trace("check can " + orgRoles + " " + op + "Own for " + this.resource);
var organizationOwnPermission = this.doCheck(_ac, orgRoles, op, 'Own', this.resource);

@@ -71,14 +64,10 @@ if (organizationOwnPermission.granted) {

;
// remove inexistent roles
CrudAccessControl.prototype.filteredRoles = function (_ac, roles) {
if (_.isEmpty(roles))
return [];
return roles.filter(function (role) { return _ac.hasRole(role); });
};
CrudAccessControl.prototype.getOrgRoles = function (user) {
var orgRoles = [];
orgRoles = orgRoles.concat(_.uniq(user.roles
.filter(function (role) { return role.indexOf('$organization') == 0; })
.map(function (role) { return role.replace(/:.*:/, ':'); })));
return orgRoles;
var roles = [];
if (user.organization && user.organization.ref
&& user.organization.ref.code) {
var org = user.organization;
roles.push(org.ref.code + ":" + org.role);
}
return roles;
};

@@ -85,0 +74,0 @@ return CrudAccessControl;

@@ -7,3 +7,3 @@ "use strict";

var accessControll;
var newVideo, myVideo, videoFromThirdPary, adminUser, adminUserWithOtherOtherRole, normalUser, organizationManager, guestUser;
var newVideo, myVideo, videoFromThirdPary, adminUser, normalUser, organizationManager, guestUser;
var queryMock;

@@ -20,4 +20,4 @@ accessControll = new access_control_authorization_1.CrudAccessControl('video', [

{ role: 'user', resource: 'video', action: 'delete:own', attributes: ['*'] },
{ role: '$organization:manager', resource: 'video', action: 'create:own', attributes: ['*'] },
{ role: '$organization:manager', resource: 'video', action: 'read:any', attributes: ['*'] },
{ role: '$organization:manager', resource: 'video', action: 'create:own', attributes: ['*'] },
{ role: '$organization:manager', resource: 'video', action: 'update:own', attributes: ['*'] },

@@ -30,6 +30,2 @@ { role: '$organization:manager', resource: 'video', action: 'delete:own', attributes: ['*'] }

};
adminUserWithOtherOtherRole = {
_id: '0010',
roles: ['admin', 'other1', 'other2']
};
organizationManager = {

@@ -71,9 +67,2 @@ _id: '001',

});
it('admin with not declared role bug test', function () {
var grant = accessControll.check(adminUserWithOtherOtherRole, 'read');
console.log("NOT DECLARED" + JSON.stringify(grant));
chai_1.expect(grant.granted).to.equal(true);
chai_1.expect(grant.type).to.equal('any');
chai_1.expect(grant.ownerTypes).to.be.empty;
});
it('user should be allowed to create video of its own', function () {

@@ -80,0 +69,0 @@ var grant = accessControll.check(normalUser, 'create');

export declare function checkAuthorization(op: any, req: any): (entity: any) => any;
export declare function restrictByUser(req: any): (query: any) => any;

@@ -0,0 +0,0 @@ 'use strict';

@@ -0,0 +0,0 @@ import { Request, Response } from 'express';

@@ -12,3 +12,3 @@ "use strict";

.then(entity_utils_1.createEntity(model))
.then(controller_utils_1.respondWithResult(res))
.then(controller_utils_1.respondWithResult(res, 'create'))
.catch(controller_utils_1.handleError(res));

@@ -15,0 +15,0 @@ }

@@ -0,0 +0,0 @@ export * from './logger';

@@ -0,0 +0,0 @@ "use strict";

declare const l: any;
export default l;

@@ -0,0 +0,0 @@ "use strict";

export declare function OwnerSchemaFactory(): any;

@@ -0,0 +0,0 @@ 'use strict';

@@ -0,0 +0,0 @@ 'use strict';

@@ -0,0 +0,0 @@ 'use strict';

declare var assert: any;

@@ -0,0 +0,0 @@ var assert = require('assert');

@@ -11,4 +11,4 @@ import { Model, Document, DocumentQuery } from 'mongoose';

export declare function execFindByIdWithQueryBuilder(model: Model<Document>, id: any): (queryBuilder: (query: DocumentQuery<any, any>) => DocumentQuery<any, any>) => Promise<any>;
export declare function restrictByOwner(ownerTypes: any, userId?: any, organizationCodes?: any): (query: DocumentQuery<any, any>) => DocumentQuery<any, any>;
export declare function restrictByOwner(ownerTypes: any, userId?: any, organizationCode?: any): (query: DocumentQuery<any, any>) => DocumentQuery<any, any>;
export declare function restrictByUserOwner(user: any): (query: DocumentQuery<any, any>) => DocumentQuery<any, any>;
export declare function restrictByOrganizationOwner(user: any): (query: DocumentQuery<any, any>) => DocumentQuery<any, any>;

@@ -88,3 +88,3 @@ 'use strict';

exports.execFindByIdWithQueryBuilder = execFindByIdWithQueryBuilder;
function restrictByOwner(ownerTypes, userId, organizationCodes) {
function restrictByOwner(ownerTypes, userId, organizationCode) {
var restrictions = [];

@@ -95,3 +95,3 @@ if (ownerTypes.indexOf('user') >= 0) {

if (ownerTypes.indexOf('organization') >= 0) {
restrictions.push({ "owner.organizationCode": { $in: organizationCodes } });
restrictions.push({ "owner.organizationCode": organizationCode });
}

@@ -112,11 +112,6 @@ return function (query) {

function getPopulateObject(populatePathParam) {
var completePaths = populatePathParam
.split(',')
.map(function (s) { return s.trim(); });
var completePaths = populatePathParam.split(',');
var populates = [];
completePaths.forEach(function (completePath) {
var paths = escapeInsideDots(completePath) // escape dots inside brakets ('xxx.[kkk.zzz]' => 'xxx.[kkk*zzz]')
.split('.') // ('xxx.[kkk*zzz]' => ['xxx', '[kkk*zzz]'])
.map(function (s) { return s.replace('*', '.'); }) // unscape dots (['xxx', '[kkk*zzz]'] => ['xxx', '[kkk.zzz]'])
.map(function (s) { return s.replace(/[\[\]]/g, ''); }); // remove brakets (['xxx', '[kkk.zzz]'] => ['xxx', 'kkk.zzz'])
var paths = completePath.split('.');
paths.reduce(function (fieldsToPopulate, path) {

@@ -133,19 +128,2 @@ var p = _.find(fieldsToPopulate, { path: path });

}
function escapeInsideDots(path) {
if (!path)
return;
var insideBrackets = false;
var escapedPath = "";
for (var i = 0; i < path.length; i++) {
var c = path[i];
if (c == '[')
insideBrackets = true;
if (c == ']')
insideBrackets = false;
if (c == '.' && insideBrackets == true)
c = '*';
escapedPath += c;
}
return escapedPath;
}
// deprecated

@@ -152,0 +130,0 @@ function restrictByUserOwner(user) {

import { Response } from 'express';
export declare function respondWithResult(res: Response, statusCode?: number): (entity: any) => any;
export declare function respondWithResult(res: Response, operation?: string): (entity: any) => void;
export declare function handleEntityNotFound(res: Response): (entity: any) => any;
export declare function handleError(res: any, statusCode?: number): (err: any) => void;
export declare function successMessageResult(): () => string;
export declare function baseHandle(req: any, res: Response, promisedAc: any, op: string, handleFnc: any): any;
export declare function baseHandle(req: any, res: Response, promisedAc: any, op: string, handleFnc: any): void;

@@ -6,4 +6,4 @@ "use strict";

var promise_grants_utils_1 = require("../utils/promise-grants.utils");
function respondWithResult(res, statusCode) {
statusCode = statusCode || 200;
function respondWithResult(res, operation) {
var statusCode = (operation == 'create') ? 201 : 200;
return function (entity) {

@@ -13,3 +13,2 @@ if (entity) {

}
return entity;
};

@@ -39,3 +38,2 @@ }

res.status(statusCode).send(err);
throw err;
};

@@ -52,3 +50,3 @@ }

var self = this;
return promisedAc
promisedAc
.then(function (accessControl) {

@@ -61,5 +59,5 @@ var permission = accessControl.check(req.user, op);

})
.then(self.respondWithResult(res))
.then(self.respondWithResult(res, op))
.catch(self.handleError(res));
}
exports.baseHandle = baseHandle;

@@ -7,4 +7,4 @@ import { Model, Document } from 'mongoose';

export declare function createEntity(model: Model<Document>): (entity: any) => Promise<Document>;
export declare function setUserOwner(user: any): (any) => any;
export declare function setOrganizationOwner(user: any): (any) => any;
export declare function setUserOwner(user: any): (any: any) => any;
export declare function setOrganizationOwner(user: any): (any: any) => any;
export declare function attributesFilter(filterHolder: any): (entity: any) => any;

@@ -0,0 +0,0 @@ 'use strict';

@@ -0,0 +0,0 @@ "use strict";

@@ -0,0 +0,0 @@ export declare function concatFunctions(firstFnc: any, secondFnc: any): any;

@@ -0,0 +0,0 @@ 'use strict';

import { Grant } from '../crud/access-control.authorization';
export declare function assertGranted(permission: any): any;
export declare function ifGranted(type: string, ownerType: string, grant: Grant, op: (any) => any): (any: any) => any;
export declare function ifGrantedForOwn(grant: Grant, op: (any) => any): (any: any) => any;
export declare function ifGrantedForUser(grant: Grant, op: (any) => any): (any: any) => any;
export declare function ifGrantedForOrganization(grant: Grant, op: (any) => any): (any: any) => any;
export declare function ifGrantedAny(grant: Grant, op: (any) => any): (any: any) => any;
export declare function ifGranted(type: string, ownerType: string, grant: Grant, op: (any: any) => any): (any: any) => any;
export declare function ifGrantedForOwn(grant: Grant, op: (any: any) => any): (any: any) => any;
export declare function ifGrantedForUser(grant: Grant, op: (any: any) => any): (any: any) => any;
export declare function ifGrantedForOrganization(grant: Grant, op: (any: any) => any): (any: any) => any;
export declare function ifGrantedAny(grant: Grant, op: (any: any) => any): (any: any) => any;
export declare function ifDefined(func: any): any;

@@ -0,0 +0,0 @@ 'use strict';

@@ -0,0 +0,0 @@ "use strict";

{
"name": "rhases-nodejs-commons",
"version": "0.3.5",
"version": "1.0.1",
"description": "Node.js utilities",

@@ -9,3 +9,2 @@ "main": "dist/index.js",

"test": "mocha -r ts-node/register src/**/*.spec.ts",
"testauth": "mocha -r ts-node/register src/**/*.authorization.spec.ts",
"clean": "rm -rf dist/",

@@ -15,3 +14,3 @@ "precompile": "npm run clean",

"prepublish": "npm run compile",
"release": "standard-version"
"release": "standard-version"
},

@@ -37,22 +36,22 @@ "repository": {

"accesscontrol": "^1.5.4",
"http-errors": "^1.6.2",
"lodash": "^4.17.4",
"pino": "^4.6.0",
"request": "^2.81.0"
"http-errors": "^1.7.0",
"lodash": "^4.17.10",
"pino": "^4.17.6",
"request": "^2.88.0"
},
"devDependencies": {
"@types/chai": "^4.0.4",
"@types/express": "^4.0.36",
"@types/mocha": "^2.2.43",
"@types/mongoose": "^4.7.23",
"@types/chai": "^4.1.4",
"@types/express": "^4.16.0",
"@types/mocha": "^2.2.48",
"@types/mongoose": "^4.7.39",
"chai": "^4.1.2",
"chai-as-promised": "^7.1.1",
"express": "4.x",
"mocha": "^3.5.3",
"mongoose": "4.x",
"express": "^4.16.3",
"mocha": "^5.2.0",
"mongoose": "^4.13.15",
"ntypescript": "^1.201706190042.1",
"q": "^1.5.0",
"q": "^1.5.1",
"standard-version": "^3.0.0",
"ts-node": "^3.2.0",
"typescript": "^2.5.2"
"typescript": "^2.9.2"
},

@@ -59,0 +58,0 @@ "peerDependencies": {

@@ -0,0 +0,0 @@ [![Build Status](https://travis-ci.org/rhases/rhases-nodejs-commons.svg?branch=develop)](https://travis-ci.org/rhases/rhases-nodejs-commons)

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc