strapi - restrict user to fetch only data related to him

前端 未结 3 887
执念已碎
执念已碎 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:28

    A possibility would be to extend the query used by find and findOne in the controllers with a restriction regarding the logged in user. In this case you might also want to adapt the count endpoint to be consistent.

    This would result in:

    withOwnerQuery: (ctx, ownerPath) => {
      const user = ctx.state.user;
      if (!user) {
        ctx.badRequest(null, [
          { messages: [{ id: "No authorization header was found" }] },
        ]);
        return null;
      }
      return { ...ctx.query, [ownerPath]: user.id };
    };
    
    find: async (ctx) => {
        ctx.query = withOwnerQuery(ctx, "owner.id");
        if (ctx.query._q) {
          return strapi.services.snippet.search(ctx.query);
        } else {
          return strapi.services.snippet.fetchAll(ctx.query);
        }
    },
    
    // analogous for for findOne
    

    Depending on your usage of controllers and services you could achieve the same thing via adapting the service methods.

    This kind of solution would work with the GraphQL plugin.

提交回复
热议问题