WiP on permissions
Table of shares per user
This commit is contained in:
parent
89c9615592
commit
89256d62bd
20 changed files with 354 additions and 171 deletions
1
app.js
1
app.js
|
@ -329,6 +329,7 @@ if (app.get('env') === 'development') {
|
|||
return next();
|
||||
}
|
||||
|
||||
console.log(err);
|
||||
if (req.needsJSONResponse) {
|
||||
const resp = {
|
||||
message: err.message,
|
||||
|
|
|
@ -110,19 +110,18 @@ export default class Share extends Component {
|
|||
|
||||
render() {
|
||||
const t = this.props.t;
|
||||
const roles = mailtrainConfig.roles[this.props.entityTypeId];
|
||||
|
||||
const actions = data => [
|
||||
{
|
||||
label: 'Delete',
|
||||
action: () => this.deleteShare(data[4])
|
||||
action: () => this.deleteShare(data[3])
|
||||
}
|
||||
];
|
||||
|
||||
const sharesColumns = [
|
||||
{ data: 1, title: t('Username') },
|
||||
{ data: 2, title: t('Name') },
|
||||
{ data: 3, title: t('Role'), render: data => roles[data] ? roles[data].name : data }
|
||||
{ data: 0, title: t('Username') },
|
||||
{ data: 1, title: t('Name') },
|
||||
{ data: 2, title: t('Role') }
|
||||
];
|
||||
|
||||
|
||||
|
@ -144,13 +143,6 @@ export default class Share extends Component {
|
|||
];
|
||||
|
||||
|
||||
const rolesData = [];
|
||||
for (const key in roles) {
|
||||
const role = roles[key];
|
||||
rolesData.push([ key, role.name, role.description ]);
|
||||
}
|
||||
|
||||
|
||||
if (this.state.entity) {
|
||||
return (
|
||||
<div>
|
||||
|
@ -158,8 +150,8 @@ export default class Share extends Component {
|
|||
|
||||
<h3 className="legend">{t('Add User')}</h3>
|
||||
<Form stateOwner={this} onSubmitAsync={::this.submitHandler}>
|
||||
<TableSelect ref={node => this.usersTableSelect = node} id="userId" label={t('User')} withHeader dropdown dataUrl={`/rest/shares-users-table/${this.props.entityTypeId}/${this.state.entityId}`} columns={usersColumns} selectionLabelIndex={usersLabelIndex}/>
|
||||
<TableSelect id="role" label={t('Role')} withHeader dropdown data={rolesData} columns={rolesColumns} selectionLabelIndex={1}/>
|
||||
<TableSelect ref={node => this.usersTableSelect = node} id="userId" label={t('User')} withHeader dropdown dataUrl={`/rest/shares-unassigned-users-table/${this.props.entityTypeId}/${this.state.entityId}`} columns={usersColumns} selectionLabelIndex={usersLabelIndex}/>
|
||||
<TableSelect id="role" label={t('Role')} withHeader dropdown dataUrl={`/rest/shares-roles-table/${this.props.entityTypeId}`} columns={rolesColumns} selectionLabelIndex={1}/>
|
||||
|
||||
<ButtonRow>
|
||||
<Button type="submit" className="btn-primary" icon="ok" label={t('Share')}/>
|
||||
|
@ -169,7 +161,7 @@ export default class Share extends Component {
|
|||
<hr/>
|
||||
<h3 className="legend">{t('Existing Users')}</h3>
|
||||
|
||||
<Table ref={node => this.sharesTable = node} withHeader dataUrl={`/rest/shares-table/${this.props.entityTypeId}/${this.state.entityId}`} columns={sharesColumns} actions={actions}/>
|
||||
<Table ref={node => this.sharesTable = node} withHeader dataUrl={`/rest/shares-table-by-entity/${this.props.entityTypeId}/${this.state.entityId}`} columns={sharesColumns} actions={actions}/>
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
|
|
93
client/src/shares/UserShares.js
Normal file
93
client/src/shares/UserShares.js
Normal file
|
@ -0,0 +1,93 @@
|
|||
'use strict';
|
||||
|
||||
import React, { Component } from 'react';
|
||||
import { translate } from 'react-i18next';
|
||||
import { requiresAuthenticatedUser, withPageHelpers, Title } from '../lib/page';
|
||||
import { withErrorHandling, withAsyncErrorHandler } from '../lib/error-handling';
|
||||
import { Table } from '../lib/table';
|
||||
import axios from '../lib/axios';
|
||||
import mailtrainConfig from 'mailtrainConfig';
|
||||
|
||||
@translate()
|
||||
@withPageHelpers
|
||||
@withErrorHandling
|
||||
@requiresAuthenticatedUser
|
||||
export default class UserShares extends Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
|
||||
this.sharesTables = {};
|
||||
|
||||
this.state = {
|
||||
userId: parseInt(props.match.params.id)
|
||||
};
|
||||
}
|
||||
|
||||
@withAsyncErrorHandler
|
||||
async loadEntity() {
|
||||
const response = await axios.get(`/rest/users/${this.state.userId}`);
|
||||
this.setState({
|
||||
username: response.data.username
|
||||
});
|
||||
}
|
||||
|
||||
@withAsyncErrorHandler
|
||||
async deleteShare(entityTypeId, entityId) {
|
||||
const data = {
|
||||
entityTypeId,
|
||||
entityId,
|
||||
userId: this.state.userId
|
||||
};
|
||||
|
||||
await axios.put('/rest/shares', data);
|
||||
for (const key in this.sharesTables) {
|
||||
this.sharesTables[key].refresh();
|
||||
}
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
this.loadEntity();
|
||||
}
|
||||
|
||||
render() {
|
||||
const renderSharesTable = (entityTypeId, title) => {
|
||||
const actions = data => {
|
||||
const actions = [];
|
||||
const perms = data[3];
|
||||
|
||||
if (perms.includes('share')) {
|
||||
actions.push({
|
||||
label: 'Delete',
|
||||
action: () => this.deleteShare(entityTypeId, data[2])
|
||||
});
|
||||
}
|
||||
|
||||
return actions;
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{ data: 0, title: t('Name') },
|
||||
{ data: 1, title: t('Role') }
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h3>{title}</h3>
|
||||
<Table ref={node => this.sharesTables[entityTypeId] = node} withHeader dataUrl={`/rest/shares-table-by-user/${entityTypeId}/${this.state.userId}`} columns={columns} actions={actions}/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const t = this.props.t;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Title>{t('Shares for user "{{username}}"', {username: this.state.username})}</Title>
|
||||
|
||||
{renderSharesTable('namespace', t('Namespaces'))}
|
||||
{renderSharesTable('reportTemplate', t('Report Templates'))}
|
||||
{renderSharesTable('report', t('Reports'))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
|
@ -24,9 +24,7 @@ export default class CUD extends Component {
|
|||
|
||||
this.passwordValidator = passwordValidator(props.t);
|
||||
|
||||
this.state = {
|
||||
globalRoles: []
|
||||
};
|
||||
this.state = {};
|
||||
|
||||
if (props.edit) {
|
||||
this.state.entityId = parseInt(props.match.params.id);
|
||||
|
@ -49,14 +47,6 @@ export default class CUD extends Component {
|
|||
return this.props.match.params.action === 'delete';
|
||||
}
|
||||
|
||||
@withAsyncErrorHandler
|
||||
async fetchGlobalRoles() {
|
||||
const result = await axios.get('/rest/users-global-roles');
|
||||
this.setState({
|
||||
globalRoles: result.data
|
||||
});
|
||||
}
|
||||
|
||||
@withAsyncErrorHandler
|
||||
async loadFormValues() {
|
||||
await this.getFormValuesFromURL(`/rest/users/${this.state.entityId}`, data => {
|
||||
|
@ -221,20 +211,12 @@ export default class CUD extends Component {
|
|||
const userId = this.getFormValue('id');
|
||||
const canDelete = userId !== 1 && mailtrainConfig.userId !== userId;
|
||||
|
||||
const roles = mailtrainConfig.roles.global;
|
||||
|
||||
const rolesColumns = [
|
||||
{ data: 1, title: "Name" },
|
||||
{ data: 2, title: "Description" },
|
||||
];
|
||||
|
||||
|
||||
const rolesData = [];
|
||||
for (const key in roles) {
|
||||
const role = roles[key];
|
||||
rolesData.push([ key, role.name, role.description ]);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{edit && canDelete &&
|
||||
|
@ -258,7 +240,7 @@ export default class CUD extends Component {
|
|||
<InputField id="password2" label={t('Repeat Password')} type="password"/>
|
||||
</div>
|
||||
}
|
||||
<TableSelect id="role" label={t('Role')} withHeader dropdown data={rolesData} columns={rolesColumns} selectionLabelIndex={1}/>
|
||||
<TableSelect id="role" label={t('Role')} withHeader dropdown dataUrl={'/rest/shares-roles-table/global'} columns={rolesColumns} selectionLabelIndex={1}/>
|
||||
<NamespaceSelect/>
|
||||
|
||||
<ButtonRow>
|
||||
|
|
|
@ -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 (
|
||||
<div>
|
||||
|
|
|
@ -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 => (<CUD edit {...props} />)
|
||||
};
|
||||
|
||||
subPaths.create = {
|
||||
title: t('Create User'),
|
||||
render: props => (<CUD {...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 => (<CUD edit {...props} />)
|
||||
},
|
||||
create: {
|
||||
title: t('Create User'),
|
||||
render: props => (<CUD {...props} />)
|
||||
},
|
||||
shares: {
|
||||
title: t('User Shares'),
|
||||
params: [':id' ],
|
||||
component: UserShares
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
5
index.js
5
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.
|
||||
});
|
||||
|
||||
|
||||
|
|
|
@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -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));
|
||||
}
|
||||
|
||||
|
|
|
@ -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,
|
||||
|
|
130
models/shares.js
130
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
|
||||
};
|
|
@ -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,
|
||||
|
|
|
@ -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 = {
|
||||
|
|
|
@ -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);
|
||||
});
|
||||
|
|
|
@ -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));
|
||||
});
|
||||
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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();
|
||||
});
|
||||
|
||||
|
|
|
@ -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;
|
||||
};
|
|
@ -71,6 +71,7 @@ class DependencyNotFoundError extends InteroperableError {
|
|||
class PermissionDeniedError extends InteroperableError {
|
||||
constructor(msg, data) {
|
||||
super('PermissionDeniedError', msg, data);
|
||||
this.status = 403;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue