1

I added a new filed called config (type: json) to the User model. I use built-in swagger of Strapi local document. The problem is that I can update another user config (data) with put method.

  1. First, I authorized by POST /auth/local and get my token and my user id (in this cast it's 5)
  2. I add my token to swagger Authorize button.
  3. Then, I use PUT /user/{id} in this case id is 5.
  4. Calling api http://localhost:1337/api/users/4 returns 200!

I expect that I get 403 error! Because I should not able to change other user profiles!!! Is it normal? If yes, tell me a solution to fix this.

2
  • The link to the documentation is a link to localhost. I don't have this documentation on my system. Commented Dec 8, 2022 at 9:44
  • I mean that I use default swagger. @jebaa Commented Dec 8, 2022 at 13:24

1 Answer 1

6

This is because Strapi has only two default roles:

  • Public
  • Authenticated

So by default, when you setup permissions, whatever authentication state currently the user has access to all the content accordingly (e.g. Public to only public, Authenticated to authenticated)

To work with this, and to limit the user actions in the auth scope you have to use middleware or policy, so since this is in user-permissions scope let's add policy to user-permissions:

Strapi 4.5.3

yarn strapi generate

? Strapi Generatos
>policy

? Policy name 
isOwner

? Where do you want to add this policy?
> Add policy to root of project

Next step is in your /src/extensions folder you have to create folder users-permissions, and in this folder file strapi-server.js with following content:

/src/extensions/users-permissions/strapi-server.js

module.exports = (plugin) => {
  for (let i = 0; i < plugin.routes["content-api"].routes.length; i++) {
    const route = plugin.routes["content-api"].routes[i];
    if (
      route.method === "GET" &&
      route.path === "/users/:id" &&
      route.handler === "user.findOne"
    ) {
      console.log(route);
      plugin.routes["content-api"].routes[i] = {
        ...route,
        config: {
          ...route.config,
          policies: route.config.policies
            ? [...route.config.policies, "global::isOwner"] // tests if policies were defined
            : ["global::isOwner"],
        },
      };
    }
  }

  return plugin;
};

if you did the step correct in your strapi server console you have to see: info: In isOwner policy. if you send get request to /api/users/:id

Next step is we are going to modify policy file like so: /src/policies/isOwner.js

"use strict";

/**
 * `isOwner` policy
 */

module.exports = async (policyContext, config, { strapi }) => {
  strapi.log.info("In isOwner policy.");
  const { user, auth } = policyContext.state;
  const { params } = policyContext;

  // this case the userId is the same as the id we are requesting
  // other cases would need more extensive validation...
  const canDoSomething = user.id == params.id;

  if (canDoSomething) {
    return true;
  }

  return false;
};

and whoala:

{
    "data": null,
    "error": {
        "status": 403,
        "name": "PolicyError",
        "message": "Policy Failed",
        "details": {}
    }
}

if we try to get other user profile

Version with middleware Private strapi data for current user

Sign up to request clarification or add additional context in comments.

3 Comments

would even be better throwing an error: if (!canDoSomething){ throw new PolicyError('You must be the owner of the entity to do this.', { policy: 'isOwner' }) }else{ return true; }
amazing it works perfectly in the case of managing the user-permissions. What if I want to do the same restriction but on another table where the userId is a simple parameter ?(and not the table id)
you are going to need to do an extra const {userId} = await strapi.db.query(...).find(...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.