Skip to content

Instantly share code, notes, and snippets.

@mdzzohrabi
Last active March 5, 2022 13:33
Show Gist options
  • Save mdzzohrabi/e01377c331fe7d381b68acfce0c4e28e to your computer and use it in GitHub Desktop.
Save mdzzohrabi/e01377c331fe7d381b68acfce0c4e28e to your computer and use it in GitHub Desktop.
Strapi Restrict User to Retrieve data only related to him (Strapi V4.0)
/**
* Strapi Restrict User to Retrieve data only related to him (Strapi V4.0)
*
* @author Masoud Zohrabi <[email protected]>
*/
module.exports = (ctx, config, {strapi}) => {
// Assert user logged-in
if (!ctx.state.user) return false;
// Rest API
if (ctx.request) {
// Check user query
if (ctx.request.query?.user && ctx.request.query?.user == ctx.state.user.id)
return true;
// Set user filter
if (!ctx.request.query.user) {
ctx.request.query.user = ctx.state.user.id;
return true;
}
// GraphQL
} else if (ctx.info) {
ctx.args.filters = ctx.args.filters || {};
ctx.args.filters.user = { id: { eq: ctx.state.user.id } };
return true;
}
// Deny access
return false;
}
@mdzzohrabi
Copy link
Author

Usage Example

Register GraphQL Policy

// src/index.js

'use strict';

module.exports = {
  /**
   * An asynchronous register function that runs before
   * your application is initialized.
   *
   * This gives you an opportunity to extend code.
   */
  register({ strapi }) {
    // GraphQL Policy
    const extensionService = strapi.plugin('graphql').service('extension');
    extensionService.use({
      resolversConfig: {
        'Query.posts': {
          policies: [
            'global::restrict-user'
          ]
        }
      }
    })

  },

  /**
   * An asynchronous bootstrap function that runs before
   * your application gets started.
   *
   * This gives you an opportunity to set up your data model,
   * run jobs, or perform some special logic.
   */
  bootstrap(/*{ strapi }*/) {},
};

Apply Policy on Controller (REST)

// src/api/post/routes/post.js

'use strict';

/**
 * post router.
 */

const { createCoreRouter } = require('@strapi/strapi').factories;

module.exports = createCoreRouter('api::post.post', {   
    config: {
        find: {
            policies: ['global::restrict-user']
        }
    }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment