Skip to content

Instantly share code, notes, and snippets.

@n2o
Created February 16, 2023 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n2o/7567d721b812b08e6a19a3d1e2bffd0f to your computer and use it in GitHub Desktop.
Save n2o/7567d721b812b08e6a19a3d1e2bffd0f to your computer and use it in GitHub Desktop.
Grant Privileges to a Role in Strapi (e.g. for testing)

To give access to a role from the users-permissions model in Strapi v4, you need to create a permission and add it to the role.

Useful for testing. Gives authenticated users access to the provided routes.

import request from "supertest";
import { setupStrapi, stopStrapi } from "../../../../tests/helpers/strapi";
import { createUser } from "../../../../tests/user/factory";

let user;

beforeAll(async () => {
  await setupStrapi();
  user = await createUser();
  user.jwt = strapi.plugins["users-permissions"].services.jwt.issue({
    id: user.id,
  });
});

afterAll(async () => {
  await stopStrapi();
});

describe("Testing playlists", () => {
  it("Registered users can create playlists", async () => {
    await grantPrivileges(["api::playlist.playlist.create"]);

    await request(strapi.server.httpServer)
      .post("/api/playlists")
      .set("Authorization", "bearer " + user.jwt)
      .set("accept", "application/json")
      .set("Content-Type", "application/json")
      .send({
        data: {
          title: "Awesome Playlist",
        },
      })
      .expect("Content-Type", /json/)
      .expect(200)
      .then(async (data) => {
        expect(data).toBeDefined();
      });
  });
});

// -----------------------------------------------------------------------------

async function grantPrivileges(actions: string[]) {
  const authenticatedRole = await strapi.entityService.findOne(
    "plugin::users-permissions.role",
    1,
    {
      populate: ["permissions"],
    }
  );

  const existingPermissionIds = authenticatedRole.permissions.map((p) => p.id);

  const newPermissionIds = await Promise.all(
    actions.map(async (action) => {
      const permission = await strapi.entityService.create(
        "plugin::users-permissions.permission",
        {
          data: {
            action,
          },
        }
      );
      return permission.id;
    })
  );

  const permissionIds = [...existingPermissionIds, ...newPermissionIds];

  await strapi.entityService.update("plugin::users-permissions.role", 1, {
    populate: ["permissions"],
    data: { permissions: permissionIds },
  });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment