'use strict'; const _ = require('lodash'); const CRUD = ['create', 'read', 'update', 'delete'].reverse(); // should be in format `entity:number` or `entity:action` or `entity:action1,action2,action3` // a user that can only create has 1000 bits > 8, only delete 0001 > 1, everything 1111 > 15 module.exports = function parsePermissions(permissions) { if (!Array.isArray(permissions)) { permissions = [ permissions ]; } return permissions.reduce((result, str) => { let [ entity, actions ] = str.split(':'); let integer = actions ? +actions : 0; if (!_.isNumber(integer)) { actions = actions.split(',') integer = actions.reduce((result, action) => { const index = CRUD.indexOf(action); if (index < 0) { throw new Error(`Unkown action "${action}"`); } return result & 2^index; }, 0); } if (integer > 0) { result[entity] = integer; } return result; }, {}); };