diff --git a/client/src/users/List.js b/client/src/users/List.js
index ec56ecba..b85215d7 100644
--- a/client/src/users/List.js
+++ b/client/src/users/List.js
@@ -21,6 +21,10 @@ export default class List extends Component {
{
label: 'Edit',
link: '/users/edit/' + data[0]
+ },
+ {
+ label: 'Shares',
+ link: '/users/shares/' + data[0]
}
];
@@ -34,6 +38,7 @@ export default class List extends Component {
}
columns.push({ data: 3, title: "Namespace" });
+ columns.push({ data: 4, title: "Role" });
return (
diff --git a/client/src/users/root.js b/client/src/users/root.js
index edb7a011..2c47d4fa 100644
--- a/client/src/users/root.js
+++ b/client/src/users/root.js
@@ -8,24 +8,9 @@ import i18n from '../lib/i18n';
import { Section } from '../lib/page';
import CUD from './CUD';
import List from './List';
-import mailtrainConfig from 'mailtrainConfig';
+import UserShares from '../shares/UserShares';
const getStructure = t => {
- const subPaths = {};
-
- if (mailtrainConfig.isAuthMethodLocal) {
- subPaths.edit = {
- title: t('Edit User'),
- params: [':id', ':action?'],
- render: props => ()
- };
-
- subPaths.create = {
- title: t('Create User'),
- render: props => ()
- };
- }
-
return {
'': {
title: t('Home'),
@@ -35,7 +20,22 @@ const getStructure = t => {
title: t('Users'),
link: '/users',
component: List,
- children: subPaths
+ children: {
+ edit: {
+ title: t('Edit User'),
+ params: [':id', ':action?'],
+ render: props => ()
+ },
+ create: {
+ title: t('Create User'),
+ render: props => ()
+ },
+ shares: {
+ title: t('User Shares'),
+ params: [':id' ],
+ component: UserShares
+ }
+ }
}
}
}
diff --git a/index.js b/index.js
index bedc794d..3e6aa17f 100644
--- a/index.js
+++ b/index.js
@@ -146,8 +146,9 @@ dbcheck(err => {
// And now the current migration with Knex
knex.migrate.latest()
- .then(() => shares.rebuildPermissions())
- .then(() => server.listen(port, host)); // Listen on provided port, on all network interfaces.
+ .then(() => shares.regenerateRoleNamesTable())
+ .then(() => shares.rebuildPermissions())
+ .then(() => server.listen(port, host)); // Listen on provided port, on all network interfaces.
});
diff --git a/lib/client-helpers.js b/lib/client-helpers.js
index 4dfee96d..a9514801 100644
--- a/lib/client-helpers.js
+++ b/lib/client-helpers.js
@@ -15,24 +15,8 @@ function getAnonymousConfig(context) {
}
function getAuthenticatedConfig(context) {
- const roles = {};
- for (const entityTypeId in config.roles) {
- const rolesPerEntityType = {};
- for (const roleId in config.roles[entityTypeId]) {
- const roleSpec = config.roles[entityTypeId][roleId];
-
- rolesPerEntityType[roleId] = {
- name: roleSpec.name,
- description: roleSpec.description
- }
- }
- roles[entityTypeId] = rolesPerEntityType;
- }
-
-
return {
- userId: context.user.id,
- roles
+ userId: context.user.id
}
}
diff --git a/lib/dt-helpers.js b/lib/dt-helpers.js
index b054059a..801f9953 100644
--- a/lib/dt-helpers.js
+++ b/lib/dt-helpers.js
@@ -98,7 +98,7 @@ async function ajaxList(params, queryFun, columns, mapFun) {
});
}
-async function ajaxListWithPermissions(context, fetchSpecs, params, queryFun, columns) {
+async function ajaxListWithPermissions(context, fetchSpecs, params, queryFun, columns, map) {
const permCols = [];
for (const fetchSpec of fetchSpecs) {
const entityType = permissions.getEntityType(fetchSpec.entityTypeId);
@@ -121,11 +121,13 @@ async function ajaxListWithPermissions(context, fetchSpecs, params, queryFun, co
for (const fetchSpec of fetchSpecs) {
const entityType = permissions.getEntityType(fetchSpec.entityTypeId);
- query = query.innerJoin(
- function () {
- return this.from(entityType.permissionsTable).select('entity').where('user', context.user.id).whereIn('operation', fetchSpec.requiredOperations).as(`permitted__${fetchSpec.entityTypeId}`);
- },
- `permitted__${fetchSpec.entityTypeId}.entity`, `${entityType.entitiesTable}.id`)
+ if (fetchSpec.requiredOperations) {
+ query = query.innerJoin(
+ function () {
+ return this.from(entityType.permissionsTable).select('entity').where('user', context.user.id).whereIn('operation', fetchSpec.requiredOperations).as(`permitted__${fetchSpec.entityTypeId}`);
+ },
+ `permitted__${fetchSpec.entityTypeId}.entity`, `${entityType.entitiesTable}.id`)
+ }
}
return query;
diff --git a/lib/passport.js b/lib/passport.js
index f2fee09a..47b524db 100644
--- a/lib/passport.js
+++ b/lib/passport.js
@@ -110,7 +110,7 @@ if (config.ldap.enabled && LdapStrategy) {
} catch (err) {
if (err instanceof interoperableErrors.NotFoundError) {
- const userId = await users.create({
+ const userId = await users.create(null, {
username: profile[config.ldap.uidTag],
role: config.ldap.newUserRole,
namespace: config.ldap.newUserNamespaceId
@@ -143,6 +143,6 @@ if (config.ldap.enabled && LdapStrategy) {
})));
passport.serializeUser((user, done) => done(null, user.id));
- passport.deserializeUser((id, done) => nodeifyPromise(users.getByIdNoPerms(id), done));
+ passport.deserializeUser((id, done) => nodeifyPromise(users.getById(null, id), done));
}
diff --git a/models/reports.js b/models/reports.js
index a43237f3..a9030b37 100644
--- a/models/reports.js
+++ b/models/reports.js
@@ -19,12 +19,10 @@ function hash(entity) {
}
async function getByIdWithTemplate(context, id) {
- await shares.enforceEntityPermission(context, 'report', id, 'view');
+ if (context) {
+ await shares.enforceEntityPermission(context, 'report', id, 'view');
+ }
- return await getByIdWithTemplateNoPerms(id);
-}
-
-async function getByIdWithTemplateNoPerms(id) {
const entity = await knex('reports')
.where('reports.id', id)
.innerJoin('report_templates', 'reports.report_template', 'report_templates.id')
@@ -201,7 +199,6 @@ module.exports = {
ReportState,
hash,
getByIdWithTemplate,
- getByIdWithTemplateNoPerms,
listDTAjax,
create,
updateWithConsistencyCheck,
diff --git a/models/shares.js b/models/shares.js
index 3ad46b0b..4589e052 100644
--- a/models/shares.js
+++ b/models/shares.js
@@ -9,12 +9,45 @@ const permissions = require('../lib/permissions');
const interoperableErrors = require('../shared/interoperable-errors');
-async function listDTAjax(context, entityTypeId, entityId, params) {
+async function listByEntityDTAjax(context, entityTypeId, entityId, params) {
const entityType = permissions.getEntityType(entityTypeId);
await enforceEntityPermission(context, entityTypeId, entityId, 'share');
- return await dtHelpers.ajaxList(params, builder => builder.from(entityType.sharesTable).innerJoin('users', entityType.sharesTable + '.user', 'users.id').where(`${entityType.sharesTable}.entity`, entityId), [entityType.sharesTable + '.id', 'users.username', 'users.name', entityType.sharesTable + '.role', 'users.id']);
+ return await dtHelpers.ajaxList(
+ params,
+ builder => builder
+ .from(entityType.sharesTable)
+ .innerJoin('users', entityType.sharesTable + '.user', 'users.id')
+ .innerJoin('generated_role_names', 'generated_role_names.role', 'users.role')
+ .where('generated_role_names.entity_type', entityTypeId)
+ .where(`${entityType.sharesTable}.entity`, entityId),
+ [ 'users.username', 'users.name', 'generated_role_names.name', 'users.id' ]
+ );
+}
+
+async function listByUserDTAjax(context, entityTypeId, userId, params) {
+ const user = await knex('users').where('id', userId).first();
+ if (!user) {
+ shares.throwPermissionDenied();
+ }
+
+ await enforceEntityPermission(context, 'namespace', user.namespace, 'manageUsers');
+
+ const entityType = permissions.getEntityType(entityTypeId);
+
+ return await dtHelpers.ajaxListWithPermissions(
+ context,
+ [{ entityTypeId }],
+ params,
+ builder => builder
+ .from(entityType.sharesTable)
+ .innerJoin(entityType.entitiesTable, entityType.sharesTable + '.entity', entityType.entitiesTable + '.id')
+ .innerJoin('generated_role_names', 'generated_role_names.role', entityType.sharesTable + '.role')
+ .where('generated_role_names.entity_type', entityTypeId)
+ .where(entityType.sharesTable + '.user', userId),
+ [ entityType.entitiesTable + '.name', 'generated_role_names.name', entityType.entitiesTable + '.id' ]
+ );
}
async function listUnassignedUsersDTAjax(context, entityTypeId, entityId, params) {
@@ -24,10 +57,28 @@ async function listUnassignedUsersDTAjax(context, entityTypeId, entityId, params
return await dtHelpers.ajaxList(
params,
- builder => builder.from('users').whereNotExists(function() { return this.select('*').from(entityType.sharesTable).whereRaw(`users.id = ${entityType.sharesTable}.user`).andWhere(`${entityType.sharesTable}.entity`, entityId); }),
- ['users.id', 'users.username', 'users.name']);
+ builder => builder
+ .from('users')
+ .whereNotExists(function() {
+ return this
+ .select('*')
+ .from(entityType.sharesTable)
+ .whereRaw(`users.id = ${entityType.sharesTable}.user`)
+ .andWhere(`${entityType.sharesTable}.entity`, entityId);
+ }),
+ ['users.id', 'users.username', 'users.name']
+ );
}
+async function listRolesDTAjax(context, entityTypeId, params) {
+ return await dtHelpers.ajaxList(
+ params,
+ builder => builder
+ .from('generated_role_names')
+ .where({entity_type: entityTypeId}),
+ ['role', 'name', 'description']
+ );
+}
async function assign(context, entityTypeId, entityId, userId, role) {
const entityType = permissions.getEntityType(entityTypeId);
@@ -38,13 +89,13 @@ async function assign(context, entityTypeId, entityId, userId, role) {
enforce(await tx('users').where('id', userId).select('id').first(), 'Invalid user id');
enforce(await tx(entityType.entitiesTable).where('id', entityId).select('id').first(), 'Invalid entity id');
- const entry = await tx(entityType.sharesTable).where({user: userId, entity: entityId}).select('id', 'role').first();
+ const entry = await tx(entityType.sharesTable).where({user: userId, entity: entityId}).select('role').first();
if (entry) {
if (!role) {
- await tx(entityType.sharesTable).where('id', entry.id).del();
+ await tx(entityType.sharesTable).where({user: userId, entity: entityId}).del();
} else if (entry.role !== role) {
- await tx(entityType.sharesTable).where('id', entry.id).update('role', role);
+ await tx(entityType.sharesTable).where({user: userId, entity: entityId}).update('role', role);
}
} else {
await tx(entityType.sharesTable).insert({
@@ -100,7 +151,7 @@ async function _rebuildPermissions(tx, restriction) {
})
.select(['users.id', 'users.namespace', 'users.role as userRole', `${namespaceEntityType.sharesTable}.role`]);
if (restriction.userId) {
- usersWithRoleInOwnNamespaceQuery.where('user', restriction.userId);
+ usersWithRoleInOwnNamespaceQuery.where('users.id', restriction.userId);
}
const usersWithRoleInOwnNamespace = await usersWithRoleInOwnNamespaceQuery;
@@ -118,11 +169,13 @@ async function _rebuildPermissions(tx, restriction) {
const usersWithRoleInRootNamespaceQuery = tx('users')
- .leftJoin(namespaceEntityType.sharesTable, 'users.id', `${namespaceEntityType.sharesTable}.user`)
- .where(`${namespaceEntityType.sharesTable}.entity`, 1 /* Global namespace id */)
+ .leftJoin(namespaceEntityType.sharesTable, {
+ 'users.id': `${namespaceEntityType.sharesTable}.user`,
+ [`${namespaceEntityType.sharesTable}.entity`]: 1 /* Global namespace id */
+ })
.select(['users.id', 'users.role as userRole', `${namespaceEntityType.sharesTable}.role`]);
if (restriction.userId) {
- usersWithRoleInRootNamespaceQuery.andWhere('user', restriction.userId);
+ usersWithRoleInRootNamespaceQuery.andWhere('users.id', restriction.userId);
}
const usersWithRoleInRootNamespace = await usersWithRoleInRootNamespaceQuery;
@@ -292,7 +345,6 @@ async function _rebuildPermissions(tx, restriction) {
}
}
-
async function rebuildPermissions(tx, restriction) {
restriction = restriction || {};
@@ -305,10 +357,50 @@ async function rebuildPermissions(tx, restriction) {
}
}
+async function regenerateRoleNamesTable() {
+ await knex.transaction(async tx => {
+ await tx('generated_role_names').del();
+
+ const entityTypeIds = ['global', ...Object.keys(permissions.getEntityTypes())];
+
+ for (const entityTypeId of entityTypeIds) {
+ const roles = config.roles[entityTypeId];
+
+ for (const role in roles) {
+ await tx('generated_role_names').insert({
+ entity_type: entityTypeId,
+ role,
+ name: roles[role].name,
+ description: roles[role].description,
+ });
+ }
+ }
+ });
+}
+
+
function throwPermissionDenied() {
throw new interoperableErrors.PermissionDeniedError(_('Permission denied'));
}
+async function removeDefaultShares(tx, user) {
+ const namespaceEntityType = permissions.getEntityType('namespace');
+
+ const roleConf = config.roles.global[user.role];
+
+ if (roleConf) {
+ const desiredRole = roleConf.rootNamespaceRole;
+
+ if (roleConf.ownNamespaceRole) {
+ await tx(namespaceEntityType.sharesTable).where({ user: user.id, entity: user.namespace }).del();
+ }
+
+ if (roleConf.rootNamespaceRole) {
+ await tx(namespaceEntityType.sharesTable).where({ user: user.id, entity: 1 /* Global namespace id */ }).del();
+ }
+ }
+}
+
function enforceGlobalPermission(context, requiredOperations) {
if (typeof requiredOperations === 'string') {
requiredOperations = [ requiredOperations ];
@@ -333,7 +425,7 @@ async function _checkPermission(context, entityTypeId, entityId, requiredOperati
requiredOperations = [ requiredOperations ];
}
- const permsQuery = await knex(entityType.permissionsTable)
+ const permsQuery = knex(entityType.permissionsTable)
.where('user', context.user.id)
.whereIn('operation', requiredOperations);
@@ -351,11 +443,11 @@ async function checkEntityPermission(context, entityTypeId, entityId, requiredOp
return false;
}
- return await _checkEntityPermission(context, entityTypeId, entityId, requiredOperations);
+ return await _checkPermission(context, entityTypeId, entityId, requiredOperations);
}
async function checkTypePermission(context, entityTypeId, requiredOperations) {
- return await _checkEntityPermission(context, entityTypeId, null, requiredOperations);
+ return await _checkPermission(context, entityTypeId, null, requiredOperations);
}
async function enforceEntityPermission(context, entityTypeId, entityId, requiredOperations) {
@@ -374,14 +466,18 @@ async function enforceTypePermission(context, entityTypeId, requiredOperations)
module.exports = {
- listDTAjax,
+ listByEntityDTAjax,
+ listByUserDTAjax,
listUnassignedUsersDTAjax,
+ listRolesDTAjax,
assign,
rebuildPermissions,
+ removeDefaultShares,
enforceEntityPermission,
enforceTypePermission,
checkEntityPermission,
checkTypePermission,
enforceGlobalPermission,
- throwPermissionDenied
+ throwPermissionDenied,
+ regenerateRoleNamesTable
};
\ No newline at end of file
diff --git a/models/users.js b/models/users.js
index eb6b0133..3100f8e5 100644
--- a/models/users.js
+++ b/models/users.js
@@ -30,7 +30,7 @@ const allowedKeys = new Set(['username', 'name', 'email', 'password', 'namespace
const ownAccountAllowedKeys = new Set(['name', 'email', 'password']);
const allowedKeysExternal = new Set(['username', 'namespace', 'role']);
const hashKeys = new Set(['username', 'name', 'email', 'namespace', 'role']);
-const shares = require('../../models/shares');
+const shares = require('./shares');
function hash(entity) {
@@ -65,10 +65,6 @@ async function getById(context, id) {
return await _getBy(context, 'id', id);
}
-async function getByIdNoPerms(id) {
- return await _getBy(null, 'id', id);
-}
-
async function serverValidate(context, data, isOwnAccount) {
const result = {};
@@ -120,12 +116,12 @@ async function listDTAjax(context, params) {
context,
[{ entityTypeId: 'namespace', requiredOperations: ['manageUsers'] }],
params,
- builder => builder.from('users').innerJoin('namespaces', 'namespaces.id', 'users.namespace'),
- ['users.id', 'users.username', 'users.name', 'namespaces.name', 'users.role'],
- data => {
- const role = data[4];
- data[4] = config.roles.global[role] ? config.roles.global[role].name : role;
- }
+ builder => builder
+ .from('users')
+ .innerJoin('namespaces', 'namespaces.id', 'users.namespace')
+ .innerJoin('generated_role_names', 'generated_role_names.role', 'users.role')
+ .where('generated_role_names.entity_type', 'global'),
+ [ 'users.id', 'users.username', 'users.name', 'namespaces.name', 'generated_role_names.name' ]
);
}
@@ -172,28 +168,39 @@ async function _validateAndPreprocess(tx, user, isCreate, isOwnAccount) {
}
}
-async function create(user) {
- await shares.enforceEntityPermission(context, 'namespace', user.namespace, 'manageUsers');
+async function create(context, user) {
+ if (context) { // Is also called internally from ldap handling in passport
+ await shares.enforceEntityPermission(context, 'namespace', user.namespace, 'manageUsers');
+ }
await knex.transaction(async tx => {
if (passport.isAuthMethodLocal) {
await _validateAndPreprocess(tx, user, true);
+
const userId = await tx('users').insert(filterObject(user, allowedKeys));
+
+ await shares.rebuildPermissions(tx, { userId });
+
return userId;
} else {
const filteredUser = filterObject(user, allowedKeysExternal);
enforce(user.role in config.roles.global, 'Unknown role');
+
await namespaceHelpers.validateEntity(tx, user);
- const userId = await knex('users').insert(filteredUser);
+
+ const userId = await tx('users').insert(filteredUser);
+
+ await shares.rebuildPermissions(tx, { userId });
+
return userId;
}
});
}
-async function updateWithConsistencyCheck(user, isOwnAccount) {
+async function updateWithConsistencyCheck(context, user, isOwnAccount) {
await knex.transaction(async tx => {
- const existing = await tx('users').where('id', user.id).first();
+ const existing = await tx('users').where(['id', 'namespace', 'role'], user.id).first();
if (!existing) {
shares.throwPermissionDenied();
}
@@ -218,7 +225,6 @@ async function updateWithConsistencyCheck(user, isOwnAccount) {
}
await tx('users').where('id', user.id).update(filterObject(user, isOwnAccount ? ownAccountAllowedKeys : allowedKeys));
-
} else {
enforce(isOwnAccount, 'Local user management is required');
enforce(user.role in config.roles.global, 'Unknown role');
@@ -226,6 +232,15 @@ async function updateWithConsistencyCheck(user, isOwnAccount) {
await tx('users').where('id', user.id).update(filterObject(user, allowedKeysExternal));
}
+
+ // Removes the default shares based on the user role and rebuilds permissions.
+ // rebuildPermissions adds the default shares based on the user role, which will reflect the changes
+ // done to the user.
+ if (existing.namespace !== user.namespace || existing.role !== user.role) {
+ await shares.removeDefaultShares(tx, existing);
+ }
+
+ await shares.rebuildPermissions(tx, { userId: user.id });
});
}
@@ -241,7 +256,7 @@ async function remove(context, userId) {
await shares.enforceEntityPermission(context, 'namespace', existing.namespace, 'manageUsers');
- await knex('users').where('id', userId).del();
+ await tx('users').where('id', userId).del();
});
}
@@ -366,7 +381,6 @@ module.exports = {
create,
hash,
getById,
- getByIdNoPerms,
serverValidate,
getByAccessToken,
getByUsername,
diff --git a/routes/reports.js b/routes/reports.js
index d7c43bcf..f5a89cd8 100644
--- a/routes/reports.js
+++ b/routes/reports.js
@@ -11,7 +11,7 @@ const router = require('../lib/router-async').create();
router.getAsync('/download/:id', passport.loggedIn, async (req, res) => {
await shares.enforceEntityPermission(req.context, 'report', req.params.id, 'viewContent');
- const report = await reports.getByIdWithTemplateNoPerms(req.params.id);
+ const report = await reports.getByIdWithTemplate(null, req.params.id);
if (report.state == reports.ReportState.FINISHED) {
const headers = {
diff --git a/routes/rest/account.js b/routes/rest/account.js
index f3fc3b67..f585707f 100644
--- a/routes/rest/account.js
+++ b/routes/rest/account.js
@@ -8,7 +8,7 @@ const router = require('../../lib/router-async').create();
router.getAsync('/account', passport.loggedIn, async (req, res) => {
- const user = await users.getByIdNoPerms(req.user.id);
+ const user = await users.getById(null, req.user.id);
user.hash = users.hash(user);
return res.json(user);
});
diff --git a/routes/rest/reports.js b/routes/rest/reports.js
index 3c1db6f6..4ccaa7e7 100644
--- a/routes/rest/reports.js
+++ b/routes/rest/reports.js
@@ -41,7 +41,7 @@ router.postAsync('/reports-table', passport.loggedIn, async (req, res) => {
router.postAsync('/report-start/:id', passport.loggedIn, passport.csrfProtection, async (req, res) => {
await shares.enforceEntityPermission(req.context, 'report', req.params.id, 'execute');
- const report = await reports.getByIdWithTemplateNoPerms(req.params.id);
+ const report = await reports.getByIdWithTemplate(null, req.params.id);
await shares.enforceEntityPermission(req.context, 'reportTemplate', report.report_template, 'execute');
await reportProcessor.start(req.params.id);
@@ -51,7 +51,7 @@ router.postAsync('/report-start/:id', passport.loggedIn, passport.csrfProtection
router.postAsync('/report-stop/:id', async (req, res) => {
await shares.enforceEntityPermission(req.context, 'report', req.params.id, 'execute');
- const report = await reports.getByIdWithTemplateNoPerms(req.params.id);
+ const report = await reports.getByIdWithTemplate(null, req.params.id);
await shares.enforceEntityPermission(req.context, 'reportTemplate', report.report_template, 'execute');
await reportProcessor.stop(req.params.id);
@@ -61,14 +61,14 @@ router.postAsync('/report-stop/:id', async (req, res) => {
router.getAsync('/report-content/:id', async (req, res) => {
await shares.enforceEntityPermission(req.context, 'report', req.params.id, 'viewContent');
- const report = await reports.getByIdWithTemplateNoPerms(req.params.id);
+ const report = await reports.getByIdWithTemplate(null, req.params.id);
res.sendFile(fileHelpers.getReportContentFile(report));
});
router.getAsync('/report-output/:id', async (req, res) => {
await shares.enforceEntityPermission(req.context, 'report', req.params.id, 'viewOutput');
- const report = await reports.getByIdWithTemplateNoPerms(req.params.id);
+ const report = await reports.getByIdWithTemplate(null, req.params.id);
res.sendFile(fileHelpers.getReportOutputFile(report));
});
diff --git a/routes/rest/shares.js b/routes/rest/shares.js
index d2901c31..760031b4 100644
--- a/routes/rest/shares.js
+++ b/routes/rest/shares.js
@@ -3,18 +3,26 @@
const passport = require('../../lib/passport');
const _ = require('../../lib/translate')._;
const shares = require('../../models/shares');
-const permissions = require('../../lib/permissions')
+const permissions = require('../../lib/permissions');
const router = require('../../lib/router-async').create();
-router.postAsync('/shares-table/:entityTypeId/:entityId', passport.loggedIn, async (req, res) => {
- return res.json(await shares.listDTAjax(req.context, req.params.entityTypeId, req.params.entityId, req.body));
+router.postAsync('/shares-table-by-entity/:entityTypeId/:entityId', passport.loggedIn, async (req, res) => {
+ return res.json(await shares.listByEntityDTAjax(req.context, req.params.entityTypeId, req.params.entityId, req.body));
});
-router.postAsync('/shares-users-table/:entityTypeId/:entityId', passport.loggedIn, async (req, res) => {
+router.postAsync('/shares-table-by-user/:entityTypeId/:userId', passport.loggedIn, async (req, res) => {
+ return res.json(await shares.listByUserDTAjax(req.context, req.params.entityTypeId, req.params.userId, req.body));
+});
+
+router.postAsync('/shares-unassigned-users-table/:entityTypeId/:entityId', passport.loggedIn, async (req, res) => {
return res.json(await shares.listUnassignedUsersDTAjax(req.context, req.params.entityTypeId, req.params.entityId, req.body));
});
+router.postAsync('/shares-roles-table/:entityTypeId', passport.loggedIn, async (req, res) => {
+ return res.json(await shares.listRolesDTAjax(req.context, req.params.entityTypeId, req.body));
+});
+
router.putAsync('/shares', passport.loggedIn, async (req, res) => {
const body = req.body;
await shares.assign(req.context, body.entityTypeId, body.entityId, body.userId, body.role);
diff --git a/routes/rest/users.js b/routes/rest/users.js
index 027ac6f3..a2674f75 100644
--- a/routes/rest/users.js
+++ b/routes/rest/users.js
@@ -16,7 +16,7 @@ router.getAsync('/users/:userId', passport.loggedIn, async (req, res) => {
});
router.postAsync('/users', passport.loggedIn, passport.csrfProtection, async (req, res) => {
- await users.create(req.body);
+ await users.create(req.context, req.body);
return res.json();
});
@@ -24,7 +24,7 @@ router.putAsync('/users/:userId', passport.loggedIn, passport.csrfProtection, as
const user = req.body;
user.id = parseInt(req.params.userId);
- await users.updateWithConsistencyCheck(user);
+ await users.updateWithConsistencyCheck(req.context, user);
return res.json();
});
diff --git a/setup/knex/migrations/20170507084114_create_permissions.js b/setup/knex/migrations/20170507084114_create_permissions.js
index 41ad6fe9..f1f684d9 100644
--- a/setup/knex/migrations/20170507084114_create_permissions.js
+++ b/setup/knex/migrations/20170507084114_create_permissions.js
@@ -1,39 +1,46 @@
-const shareableEntityTypes = ['list', 'report', 'report_template', 'namespace'];
-
-exports.up = function(knex, Promise) {
- let schema = knex.schema;
-
- for (const entityType of shareableEntityTypes) {
- schema = schema
- .createTable(`shares_${entityType}`, table => {
- table.increments('id').primary();
- table.integer('entity').unsigned().notNullable().references(`${entityType}s.id`).onDelete('CASCADE');
- table.integer('user').unsigned().notNullable().references('users.id').onDelete('CASCADE');
- table.string('role', 64).notNullable();
- table.unique(['entity', 'user']);
- })
- .createTable(`permissions_${entityType}`, table => {
- table.increments('id').primary();
- table.integer('entity').unsigned().notNullable().references(`${entityType}s.id`).onDelete('CASCADE');
- table.integer('user').unsigned().notNullable().references('users.id').onDelete('CASCADE');
- table.string('operation', 64).notNullable();
- table.unique(['entity', 'user', 'operation']);
- });
- }
-
- /* The global share for admin is set automatically in rebuild permissions, which is called upon every start */
-
- return schema;
-};
-
-exports.down = function(knex, Promise) {
- let schema = knex.schema;
-
- for (const entityType of shareableEntityTypes) {
- schema = schema
- .dropTable(`shares_${entityType}`)
- .dropTable(`permissions_${entityType}`);
- }
-
- return schema;
+const shareableEntityTypes = ['list', 'report', 'report_template', 'namespace'];
+
+exports.up = function(knex, Promise) {
+ let schema = knex.schema;
+
+ for (const entityType of shareableEntityTypes) {
+ schema = schema
+ .createTable(`shares_${entityType}`, table => {
+ table.integer('entity').unsigned().notNullable().references(`${entityType}s.id`).onDelete('CASCADE');
+ table.integer('user').unsigned().notNullable().references('users.id').onDelete('CASCADE');
+ table.string('role', 128).notNullable();
+ table.primary(['entity', 'user']);
+ })
+ .createTable(`permissions_${entityType}`, table => {
+ table.integer('entity').unsigned().notNullable().references(`${entityType}s.id`).onDelete('CASCADE');
+ table.integer('user').unsigned().notNullable().references('users.id').onDelete('CASCADE');
+ table.string('operation', 128).notNullable();
+ table.primary(['entity', 'user', 'operation']);
+ });
+ }
+ /* The global share for admin is set automatically in rebuildPermissions, which is called upon every start */
+
+ schema = schema
+ .createTable('generated_role_names', table => {
+ table.string('entity_type', 32).notNullable();
+ table.string('role', 128).notNullable();
+ table.string('name');
+ table.string('description');
+ table.primary(['entity_type', 'role']);
+ });
+ /* The generate_role_names table is repopulated in regenerateRoleNamesTable, which is called upon every start */
+
+ return schema;
+};
+
+exports.down = function(knex, Promise) {
+ let schema = knex.schema;
+
+ for (const entityType of shareableEntityTypes) {
+ schema = schema
+ .dropTable(`shares_${entityType}`)
+ .dropTable(`permissions_${entityType}`);
+ }
+
+ return schema;
};
\ No newline at end of file
diff --git a/shared/interoperable-errors.js b/shared/interoperable-errors.js
index 24e2547d..cb42ddb0 100644
--- a/shared/interoperable-errors.js
+++ b/shared/interoperable-errors.js
@@ -71,6 +71,7 @@ class DependencyNotFoundError extends InteroperableError {
class PermissionDeniedError extends InteroperableError {
constructor(msg, data) {
super('PermissionDeniedError', msg, data);
+ this.status = 403;
}
}