strapi - restrict user to fetch only data related to him

前端 未结 3 885
执念已碎
执念已碎 2020-12-31 21:31

Usually, a logged-in user gets all entries of a Content Type.

I created a \"snippets\" content type (_id,name,content,users<<->>snippets)

3条回答
  •  清酒与你
    2020-12-31 22:13

    You could set up a /snippets/me route under the snippets config.

    That route could call the Snippets.me controller method which would check for the user then query snippets based on the user.

    So in api/snippet/config/routes.json there would be something like :

        {
          "method": "GET",
          "path": "/snippets/me",
          "handler": "Snippets.me",
          "config": {
            "policies": []
          }
        },
    

    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);
      },
    

    Then you would give authenticated users permissions for the me route not for the overall snippets route.

提交回复
热议问题