绑架-限制用户仅获取与他有关的数据 [英] strapi - restrict user to fetch only data related to him
问题描述
通常,登录的用户会获取内容类型的所有条目.
Usually, a logged-in user gets all entries of a Content Type.
我创建了一个代码段"内容类型(_id,name,content,users<<->>snippets)
I created a "snippets" content type (_id,name,content,users<<->>snippets)
<<->>
表示具有并属于许多"关系.
<<->>
means "has and belongs to many" relation.
我创建了一些测试用户并提出了一个请求:
curl -H 'Authorization: Bearer eyJ...' http://localhost:1337/snippets/
I created some test users and make a request:
curl -H 'Authorization: Bearer eyJ...' http://localhost:1337/snippets/
主要问题:经过身份验证的用户应只看到分配给他的条目.相反,登录的用户会获取所有摘要,这很糟糕.
Main Problem: an authenticated user should only see the entries assigned to him. Instead, a logged-in user gets all snippets, which is bad.
如何修改fetchAll(ctx.query);
查询以将其考虑在内,以便在/
-route-> find
-method上执行类似fetchAll(ctx.state.user.id);
的操作?
How is it possible to modify the fetchAll(ctx.query);
query to take that into account so it does something like fetchAll(ctx.state.user.id);
at the /
-route->find
-method ?
基本查找方法在这里:
find: async (ctx) => {
if (ctx.query._q) {
return strapi.services.snippet.search(ctx.query);
} else {
return strapi.services.snippet.fetchAll(ctx.query);
}
},
子问题:当我进行Bearer-Token身份验证时,stradi甚至不知道登录了哪个用户?
Sub-Question: Does strapi even know which user is logged in when I do Bearer-Token Authentication ?
推荐答案
您可以在代码段配置下设置/snippets/me路由.
You could set up a /snippets/me route under the snippets config.
该路由可以调用Snippets.me控制器方法,该方法将检查用户,然后根据用户查询代码段.
That route could call the Snippets.me controller method which would check for the user then query snippets based on the user.
所以在api/snippet/config/routes.json
中会出现类似这样的内容:
So in api/snippet/config/routes.json
there would be something like :
{
"method": "GET",
"path": "/snippets/me",
"handler": "Snippets.me",
"config": {
"policies": []
}
},
然后在控制器(api/snippet/controllers/Snippet.js
)中,您可以执行以下操作:
Then in the controller (api/snippet/controllers/Snippet.js
), you could do something like:
me: async (ctx) => {
const user = ctx.state.user;
if (!user) {
return ctx.badRequest(null, [{ messages: [{ id: 'No authorization header was found' }] }]);
}
const data = await strapi.services.snippet.fetch({user:user.id});
if(!data){
return ctx.notFound();
}
ctx.send(data);
},
然后,您将向经过身份验证的用户授予me路由权限,而不是整体代码段路由权限.
Then you would give authenticated users permissions for the me route not for the overall snippets route.
这篇关于绑架-限制用户仅获取与他有关的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!