feat(plugin-user): add model method desensitize() to filter hidden field (#3768)

* feat(plugin-user): add model method desensitize() to filter hidden field

* fix(plugin-workflow-action-trigger): fix user fields in context
This commit is contained in:
Junyi 2024-03-20 23:22:22 +08:00 committed by GitHub
parent cebb013482
commit 9b27fa955a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 48 additions and 2 deletions

View File

@ -0,0 +1,27 @@
import Database from '@nocobase/database';
import { createMockServer, MockServer } from '@nocobase/test';
import { UserModel } from '../models/UserModel';
describe('models', () => {
let app: MockServer;
let db: Database;
beforeEach(async () => {
app = await createMockServer({
plugins: ['auth', 'users'],
});
db = app.db;
});
afterEach(async () => {
await app.destroy();
});
it('model registeration', async () => {
const model = db.getModel('users');
const u1 = model.build({ nickname: 'test', password: '123' });
expect(u1).toBeInstanceOf(UserModel);
const n = u1.desensitize();
expect(n.password).toBeUndefined();
});
});

View File

@ -0,0 +1,15 @@
import { Model } from '@nocobase/database';
export class UserModel extends Model {
desensitize() {
const { fields } = (this.constructor as typeof UserModel).collection;
const result = (this.constructor as typeof UserModel).build({}, { isNewRecord: this.isNewRecord });
for (const [name, value] of Object.entries(this.get())) {
const field = fields.get(name);
if (field && !field.options.hidden) {
result.set(name, value);
}
}
return result;
}
}

View File

@ -5,9 +5,13 @@ import { resolve } from 'path';
import * as actions from './actions/users';
import { Cache } from '@nocobase/cache';
import { UserModel } from './models/UserModel';
export default class PluginUsersServer extends Plugin {
async beforeLoad() {
this.db.registerModels({
UserModel,
});
this.db.registerOperators({
$isCurrentUser(_, ctx) {
return {
@ -116,7 +120,6 @@ export default class PluginUsersServer extends Plugin {
async load() {
await this.importCollections(resolve(__dirname, 'collections'));
this.db.addMigrations({
namespace: 'users',
directory: resolve(__dirname, 'migrations'),

View File

@ -57,8 +57,9 @@ export default class extends Trigger {
const { triggerWorkflows = '', values } = context.action.params;
const { currentUser, currentRole } = context.state;
const { model: UserModel } = this.workflow.db.getCollection('users');
const userInfo = {
user: toJSON(currentUser),
user: UserModel.build(currentUser).desensitize(),
roleName: currentRole,
};