nocobase/packages/plugins/acl/src/server.ts

464 lines
14 KiB
TypeScript
Raw Normal View History

import { Context } from '@nocobase/actions';
import { Collection } from '@nocobase/database';
2022-02-11 10:13:14 +00:00
import { Plugin } from '@nocobase/server';
2022-02-11 15:59:03 +00:00
import { resolve } from 'path';
import { availableActionResource } from './actions/available-actions';
2022-03-13 11:36:37 +00:00
import { checkAction } from './actions/role-check';
2022-04-08 08:17:39 +00:00
import { roleCollectionsResource } from './actions/role-collections';
import { setDefaultRole } from './actions/user-setDefaultRole';
import { setCurrentRole } from './middlewares/setCurrentRole';
2022-02-28 06:25:50 +00:00
import { RoleModel } from './model/RoleModel';
import { RoleResourceActionModel } from './model/RoleResourceActionModel';
import { RoleResourceModel } from './model/RoleResourceModel';
export interface AssociationFieldAction {
associationActions: string[];
targetActions?: string[];
}
interface AssociationFieldActions {
[availableActionName: string]: AssociationFieldAction;
}
export interface AssociationFieldsActions {
[associationType: string]: AssociationFieldActions;
}
export class GrantHelper {
resourceTargetActionMap = new Map<string, string[]>();
targetActionResourceMap = new Map<string, string[]>();
constructor() {}
}
2022-02-11 10:13:14 +00:00
export class PluginACL extends Plugin {
// association field actions config
associationFieldsActions: AssociationFieldsActions = {};
grantHelper = new GrantHelper();
2022-02-11 15:59:03 +00:00
get acl() {
return this.app.acl;
}
2022-02-11 15:59:03 +00:00
registerAssociationFieldAction(associationType: string, value: AssociationFieldActions) {
this.associationFieldsActions[associationType] = value;
}
registerAssociationFieldsActions() {
// if grant create action to role, it should
// also grant add action and association target's view action
this.registerAssociationFieldAction('linkTo', {
view: {
associationActions: ['list', 'get'],
},
create: {
associationActions: ['add'],
targetActions: ['view'],
},
update: {
associationActions: ['add', 'remove', 'toggle'],
targetActions: ['view'],
},
});
this.registerAssociationFieldAction('attachments', {
view: {
associationActions: ['list', 'get'],
},
add: {
associationActions: ['upload', 'add'],
},
update: {
associationActions: ['update', 'add', 'remove', 'toggle'],
},
});
this.registerAssociationFieldAction('subTable', {
view: {
associationActions: ['list', 'get'],
},
create: {
associationActions: ['create'],
},
update: {
associationActions: ['update', 'destroy'],
},
});
}
async writeResourceToACL(resourceModel: RoleResourceModel, transaction) {
await resourceModel.writeToACL({
acl: this.acl,
associationFieldsActions: this.associationFieldsActions,
transaction: transaction,
grantHelper: this.grantHelper,
});
}
async writeActionToACL(actionModel: RoleResourceActionModel, transaction) {
const resource = actionModel.get('resource') as RoleResourceModel;
const role = this.acl.getRole(resource.get('roleName') as string);
await actionModel.writeToACL({
acl: this.acl,
role,
resourceName: resource.get('name') as string,
associationFieldsActions: this.associationFieldsActions,
grantHelper: this.grantHelper,
});
}
async writeRolesToACL() {
const roles = (await this.app.db.getRepository('roles').find({
appends: ['resources', 'resources.actions'],
})) as RoleModel[];
for (const role of roles) {
role.writeToAcl({ acl: this.acl });
for (const resource of role.get('resources') as RoleResourceModel[]) {
await this.writeResourceToACL(resource, null);
}
}
}
2022-02-11 11:31:53 +00:00
async beforeLoad() {
this.app.db.registerModels({
RoleResourceActionModel,
RoleResourceModel,
RoleModel,
});
this.registerAssociationFieldsActions();
this.app.resourcer.define(availableActionResource);
this.app.resourcer.define(roleCollectionsResource);
2022-03-13 11:36:37 +00:00
this.app.resourcer.registerActionHandler('roles:check', checkAction);
this.app.resourcer.registerActionHandler(`users:setDefaultRole`, setDefaultRole);
this.db.on('users.afterCreateWithAssociations', async (model, options) => {
const { transaction } = options;
const repository = this.app.db.getRepository('roles');
const defaultRole = await repository.findOne({
filter: {
default: true,
},
transaction,
});
if (defaultRole && (await model.countRoles({ transaction })) == 0) {
await model.addRoles(defaultRole, { transaction });
}
});
2022-04-11 02:09:55 +00:00
this.app.db.on('roles.afterSaveWithAssociations', async (model, options) => {
const { transaction } = options;
model.writeToAcl({
acl: this.acl,
});
2022-04-11 02:09:55 +00:00
for (const resource of (await model.getResources({ transaction })) as RoleResourceModel[]) {
await this.writeResourceToACL(resource, transaction);
}
// model is default
if (model.get('default')) {
await this.app.db.getRepository('roles').update({
values: {
default: false,
},
filter: {
'name.$ne': model.get('name'),
},
hooks: false,
transaction,
});
}
});
this.app.db.on('roles.afterDestroy', (model) => {
const roleName = model.get('name');
2022-02-11 15:59:03 +00:00
this.acl.removeRole(roleName);
});
this.app.db.on('rolesResources.afterSaveWithAssociations', async (model: RoleResourceModel, options) => {
await this.writeResourceToACL(model, options.transaction);
});
this.app.db.on('rolesResourcesActions.afterUpdateWithAssociations', async (model, options) => {
const { transaction } = options;
const resource = await model.getResource({
transaction,
});
await this.writeResourceToACL(resource, transaction);
});
this.app.db.on('rolesResources.afterDestroy', async (model, options) => {
const role = this.acl.getRole(model.get('roleName'));
if (role) {
role.revokeResource(model.get('name'));
}
});
this.app.db.on('collections.afterDestroy', async (model, options) => {
const { transaction } = options;
await this.app.db.getRepository('rolesResources').destroy({
filter: {
name: model.get('name'),
},
transaction,
});
});
this.app.db.on('fields.afterCreate', async (model, options) => {
const { transaction } = options;
const collectionName = model.get('collectionName');
const fieldName = model.get('name');
const resourceActions = (await this.app.db.getRepository('rolesResourcesActions').find({
filter: {
'resource.name': collectionName,
},
transaction,
appends: ['resource'],
})) as RoleResourceActionModel[];
for (const resourceAction of resourceActions) {
const fields = resourceAction.get('fields') as string[];
const newFields = [...fields, fieldName];
await this.app.db.getRepository('rolesResourcesActions').update({
filterByTk: resourceAction.get('id') as number,
values: {
fields: newFields,
},
transaction,
});
}
});
this.app.db.on('fields.afterDestroy', async (model, options) => {
const collectionName = model.get('collectionName');
const fieldName = model.get('name');
const resourceActions = await this.app.db.getRepository('rolesResourcesActions').find({
filter: {
'resource.name': collectionName,
'fields.$anyOf': [fieldName],
},
transaction: options.transaction,
});
for (const resourceAction of resourceActions) {
const fields = resourceAction.get('fields') as string[];
const newFields = fields.filter((field) => field != fieldName);
await this.app.db.getRepository('rolesResourcesActions').update({
filterByTk: resourceAction.get('id') as number,
values: {
fields: newFields,
},
transaction: options.transaction,
});
}
});
// sync database role data to acl
this.app.on('afterLoad', async (app, options) => {
feat: improve code (#978) * feat: 图形化管理数据表 * feat: 图形化管理数据表 * feat: 图形化管理数据表 * feat: 图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat(collection-manager): add foreignKey Field and support relate field record foreignKey info through collection record into collections and foreignKey field record info fields * fix(collection-manager): if has through collection then don't create through collections record * fix(client/route-switch): skip sub routes * feat: 添加graphpostion * feat: 图形化collection新增表时刷新数据 * fix(collection-manager): refactor afterCreateForRelateField * feat: 图形化collection存储位置 * feat: 图形化collection存储位置 * feat: 图形化collection存储位置 * feat: 图形化collection存储位置 * feat: 图形化collection存储位置 * feat: 图形化collection存储位置 * feat: 图形化collection存储位置 * feat: 图形化collection存储位置 * feat: 图形化collection存储位置 * feat: 图形化collection存储位置 * feat: 图形化样式优化 * feat: styling * feat: 图形化样式优化 * feat: 图形化样式优化 * feat: 图形化数据表多语言完善 * feat: 图形化数据表多语言完善 * feat: improve code * feat: 图形化数据表连线样式修改 * feat: 图形化数据表样式修改 * feat: 图形化数据表样式修改 * feat: 图形化数据表样式修改 * feat: 图形化数据表样式修改 * fix(collection-manager): fix afterCreateForRelateField * feat: 样式优化 * feat: 样式优化 * feat: afterCreateForForeignKeyField * fix: timestamps: false * feat: 连线锚点优化 * fix(collection-manager): when del foreign key field, relate fields will be del too * fix: update package.json * fix: update package.json * feat: 文件名大小写 * feat: 连线锚点优化 * feat: 连线锚点通过计算得到样式优化 * feat: 连线锚点通过计算得到样式优化 * fix: fk * fix: remove index * feat: 连线hover时高亮 * fix: test error * feat: 初始化计算位置 * feat: 初始化时计算坐标位置 * feat: 初始化时计算坐标位置 * feat: improve code (#933) * fix: built in * feat: 没有关系字段时也要连线 * feat: 自关联也要连线 * fix: styling * feat: 滚动条问题 * feat: 拖拽优化 * feat: 画布paddig优化 * feat: 编辑时支持反向关联字段配置 * feat: 画布拖拽滚动优化 * feat: 画布拖拽滚动优化 * fix: reload * feat: 修复数据表新建重叠 * fix: refreshCM & refreshGM * feat: 修复表达式输入框显示异常 * feat: 渲染性能优化(增量渲染) * feat: 渲染性能优化(增量渲染) * feat: 渲染性能优化(增量渲染) * fix: 消除代码警告 * fix: 消除代码警告 * feat: 渲染性能优化(增量渲染) * feat: 渲染性能优化(增量渲染) * feat: 渲染性能优化(增量渲染) * feat: 渲染性能优化(增量渲染) * feat: 渲染性能优化(增量渲染) * feat: 渲染性能优化(增量渲染) * feat: 渲染性能优化(增量渲染) * feat: 渲染性能优化 * feat: 渲染性能优化 * feat: 外键生成在位置在前面 * feat: 限制表最多显示10个字段其余滚动 * feat: 移动表位置的连线重新计算最优位置 * fix: error * feat: 布局自动换行 * fix: test error * fix: xpipe.eq * fix: upgrade error * fix: upgrade error * feat: 选中表时只显示和目标表关联的表和连线 * fix: maxListenersExceededWarning * feat: remove graph-collection-manager * fix: remove graph-collection-manager * fix: update yarn.lock Co-authored-by: 唐小爱 <tangxiaoai@192.168.0.103> Co-authored-by: lyf-coder <lyf-coder@foxmail.com> Co-authored-by: katherinehhh <katherine_15995@163.com>
2022-10-28 07:09:14 +00:00
if (options?.method === 'install') {
2022-10-27 07:32:58 +00:00
return;
}
const exists = await this.app.db.collectionExistsInDb('roles');
if (exists) {
await this.writeRolesToACL();
}
});
2022-02-28 06:25:50 +00:00
feat: improve code (#978) * feat: 图形化管理数据表 * feat: 图形化管理数据表 * feat: 图形化管理数据表 * feat: 图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 完善图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat: 样式优化图形化管理数据表 * feat(collection-manager): add foreignKey Field and support relate field record foreignKey info through collection record into collections and foreignKey field record info fields * fix(collection-manager): if has through collection then don't create through collections record * fix(client/route-switch): skip sub routes * feat: 添加graphpostion * feat: 图形化collection新增表时刷新数据 * fix(collection-manager): refactor afterCreateForRelateField * feat: 图形化collection存储位置 * feat: 图形化collection存储位置 * feat: 图形化collection存储位置 * feat: 图形化collection存储位置 * feat: 图形化collection存储位置 * feat: 图形化collection存储位置 * feat: 图形化collection存储位置 * feat: 图形化collection存储位置 * feat: 图形化collection存储位置 * feat: 图形化collection存储位置 * feat: 图形化样式优化 * feat: styling * feat: 图形化样式优化 * feat: 图形化样式优化 * feat: 图形化数据表多语言完善 * feat: 图形化数据表多语言完善 * feat: improve code * feat: 图形化数据表连线样式修改 * feat: 图形化数据表样式修改 * feat: 图形化数据表样式修改 * feat: 图形化数据表样式修改 * feat: 图形化数据表样式修改 * fix(collection-manager): fix afterCreateForRelateField * feat: 样式优化 * feat: 样式优化 * feat: afterCreateForForeignKeyField * fix: timestamps: false * feat: 连线锚点优化 * fix(collection-manager): when del foreign key field, relate fields will be del too * fix: update package.json * fix: update package.json * feat: 文件名大小写 * feat: 连线锚点优化 * feat: 连线锚点通过计算得到样式优化 * feat: 连线锚点通过计算得到样式优化 * fix: fk * fix: remove index * feat: 连线hover时高亮 * fix: test error * feat: 初始化计算位置 * feat: 初始化时计算坐标位置 * feat: 初始化时计算坐标位置 * feat: improve code (#933) * fix: built in * feat: 没有关系字段时也要连线 * feat: 自关联也要连线 * fix: styling * feat: 滚动条问题 * feat: 拖拽优化 * feat: 画布paddig优化 * feat: 编辑时支持反向关联字段配置 * feat: 画布拖拽滚动优化 * feat: 画布拖拽滚动优化 * fix: reload * feat: 修复数据表新建重叠 * fix: refreshCM & refreshGM * feat: 修复表达式输入框显示异常 * feat: 渲染性能优化(增量渲染) * feat: 渲染性能优化(增量渲染) * feat: 渲染性能优化(增量渲染) * fix: 消除代码警告 * fix: 消除代码警告 * feat: 渲染性能优化(增量渲染) * feat: 渲染性能优化(增量渲染) * feat: 渲染性能优化(增量渲染) * feat: 渲染性能优化(增量渲染) * feat: 渲染性能优化(增量渲染) * feat: 渲染性能优化(增量渲染) * feat: 渲染性能优化(增量渲染) * feat: 渲染性能优化 * feat: 渲染性能优化 * feat: 外键生成在位置在前面 * feat: 限制表最多显示10个字段其余滚动 * feat: 移动表位置的连线重新计算最优位置 * fix: error * feat: 布局自动换行 * fix: test error * fix: xpipe.eq * fix: upgrade error * fix: upgrade error * feat: 选中表时只显示和目标表关联的表和连线 * fix: maxListenersExceededWarning * feat: remove graph-collection-manager * fix: remove graph-collection-manager * fix: update yarn.lock Co-authored-by: 唐小爱 <tangxiaoai@192.168.0.103> Co-authored-by: lyf-coder <lyf-coder@foxmail.com> Co-authored-by: katherinehhh <katherine_15995@163.com>
2022-10-28 07:09:14 +00:00
this.app.on('afterInstall', async (app, options) => {
const exists = await this.app.db.collectionExistsInDb('roles');
if (exists) {
await this.writeRolesToACL();
}
});
2022-10-29 06:07:51 +00:00
this.app.on('afterInstallPlugin', async (plugin) => {
if (plugin.getName() !== 'users') {
return;
}
const User = this.db.getCollection('users');
await User.repository.update({
values: {
roles: ['root', 'admin', 'member'],
},
forceUpdate: true,
});
const RolesUsers = this.db.getCollection('rolesUsers');
await RolesUsers.repository.update({
filter: {
userId: 1,
roleName: 'root',
},
values: {
default: true,
},
});
});
2022-02-28 14:10:04 +00:00
this.app.on('beforeInstallPlugin', async (plugin) => {
2022-10-29 06:07:51 +00:00
if (plugin.getName() !== 'users') {
2022-02-28 14:10:04 +00:00
return;
}
const roles = this.app.db.getRepository('roles');
await roles.createMany({
2022-02-28 06:25:50 +00:00
records: [
{
name: 'root',
2022-04-22 15:58:19 +00:00
title: '{{t("Root")}}',
hidden: true,
},
2022-02-28 06:25:50 +00:00
{
name: 'admin',
2022-04-22 15:58:19 +00:00
title: '{{t("Admin")}}',
allowConfigure: true,
allowNewMenu: true,
strategy: { actions: ['create', 'view', 'update', 'destroy'] },
2022-02-28 06:25:50 +00:00
},
{
name: 'member',
2022-04-22 15:58:19 +00:00
title: '{{t("Member")}}',
allowNewMenu: true,
strategy: { actions: ['view', 'update:own', 'destroy:own', 'create'] },
2022-02-28 06:25:50 +00:00
default: true,
},
],
});
const rolesResourcesScopes = this.app.db.getRepository('rolesResourcesScopes');
await rolesResourcesScopes.createMany({
records: [
{
key: 'all',
name: '{{t("All records")}}',
scope: {},
},
{
key: 'own',
name: '{{t("Own records")}}',
scope: {
createdById: '{{ ctx.state.currentUser.id }}',
},
},
],
});
2022-02-28 06:25:50 +00:00
});
this.app.resourcer.use(setCurrentRole, { tag: 'setCurrentRole', before: 'acl', after: 'parseToken' });
this.app.acl.allow('users', 'setDefaultRole', 'loggedIn');
this.app.acl.allow('roles', 'check', 'loggedIn');
this.app.acl.allow('roles', ['create', 'update', 'destroy'], 'allowConfigure');
this.app.acl.allow('roles.menuUiSchemas', ['set', 'toggle', 'list'], 'allowConfigure');
this.app.acl.allow('*', '*', (ctx) => {
return ctx.state.currentRole === 'root';
});
2022-04-13 04:18:44 +00:00
this.app.resourcer.use(async (ctx, next) => {
2022-04-13 04:18:44 +00:00
const { actionName, resourceName, params } = ctx.action;
const { showAnonymous } = params || {};
if (actionName === 'list' && resourceName === 'roles') {
2022-04-13 04:18:44 +00:00
if (!showAnonymous) {
ctx.action.mergeParams({
filter: {
'name.$ne': 'anonymous',
},
});
}
}
if (actionName === 'update' && resourceName === 'roles.resources') {
ctx.action.mergeParams({
updateAssociationValues: ['actions'],
});
}
await next();
});
this.app.acl.use(async (ctx: Context, next) => {
const { actionName, resourceName } = ctx.action;
if (actionName === 'get' || actionName === 'list') {
if (!Array.isArray(ctx?.permission?.can?.params?.fields)) {
return next();
}
let collection: Collection;
if (resourceName.includes('.')) {
const [collectionName, associationName] = resourceName.split('.');
const field = ctx.db.getCollection(collectionName)?.getField?.(associationName);
if (field.target) {
collection = ctx.db.getCollection(field.target);
}
} else {
collection = ctx.db.getCollection(resourceName);
}
if (collection && collection.hasField('createdById')) {
ctx.permission.can.params.fields.push('createdById');
}
}
return next();
});
const parseJsonTemplate = this.app.acl.parseJsonTemplate;
this.app.acl.use(async (ctx: Context, next) => {
const { actionName, resourceName, resourceOf } = ctx.action;
if (resourceName.includes('.') && resourceOf) {
if (!ctx?.permission?.can?.params) {
return next();
}
// 关联数据去掉 filter
delete ctx.permission.can.params.filter;
// 关联数据能不能处理取决于 source 是否有权限
const [collectionName] = resourceName.split('.');
const action = ctx.can({ resource: collectionName, action: actionName });
const availableAction = this.app.acl.getAvailableAction(actionName);
if (availableAction?.options?.onNewRecord) {
if (action) {
ctx.permission.skip = true;
} else {
ctx.permission.can = false;
}
} else {
const filter = parseJsonTemplate(action?.params?.filter || {}, ctx);
const sourceInstance = await ctx.db.getRepository(collectionName).findOne({
filterByTk: resourceOf,
filter,
});
if (!sourceInstance) {
ctx.permission.can = false;
}
}
}
await next();
});
}
2022-03-02 10:35:49 +00:00
async install() {
const repo = this.db.getRepository<any>('collections');
if (repo) {
await repo.db2cm('roles');
}
}
async load() {
await this.app.db.import({
2022-02-11 15:59:03 +00:00
directory: resolve(__dirname, 'collections'),
});
}
}
2022-02-11 10:13:14 +00:00
export default PluginACL;