如何在Strapi中添加中间件按所有者过滤核心Find方法结果?
Strapi 实现用户仅查看自身记录的中间件方案
核心思路:提前修改查询条件,而非事后过滤
不用等控制器返回结果再手动筛选,而是在中间件阶段直接修改find方法的查询参数,让Strapi原生查询就只返回当前用户的记录,既避免了字段缺失问题,也不用暴露敏感字段。
具体实现步骤
在中间件中注入用户过滤条件
在你的自定义中间件里,先获取当前登录用户ID,再往查询参数里追加过滤规则:module.exports = (config, { strapi }) => { return async (ctx, next) => { const currentUserId = ctx.state.user?.id; if (currentUserId) { // 合并原有查询条件,避免覆盖用户传入的其他过滤参数 ctx.query.filters = { ...(ctx.query.filters || {}), // 替换成你的集合关联用户的字段名,比如`owner`或`user` user: { id: currentUserId } }; } await next(); }; };跳过特殊角色的过滤(可选)
如果需要让管理员或特定角色查看所有记录,可添加角色判断逻辑:const isAdmin = ctx.state.user?.roles.some(role => role.name === 'Administrator'); if (!isAdmin && currentUserId) { // 仅非管理员用户才应用过滤 ctx.query.filters = { ...(ctx.query.filters || {}), user: { id: currentUserId } }; }隐藏关联的用户字段
要确保用户关联字段不暴露给前端,在集合的schema.json中将该字段设为私有:{ "attributes": { "user": { "type": "relation", "relation": "manyToOne", "target": "plugin::users-permissions.user", "private": true } } }这样字段不会出现在接口响应中,但依然能作为查询过滤的依据。
配置中间件挂载
在config/middlewares.js中指定中间件应用的集合和方法:module.exports = [ // 其他中间件... { name: 'global::user-record-filter', // 你的中间件名称 config: { applyTo: { contentTypes: ['api::post.post'], // 替换成你的集合名 methods: ['find'] } } } ];
内容的提问来源于stack exchange,提问作者Unknow
相关产品推荐
相关产品推荐

