Set permissions programmatically? #6294

This discussion has been migrated from our Github Discussion #6294


laggingreflex216d ago

I have a collection type “Content

The normal API route to get all contents is GET /contents

But by default it’s inaccessible, and gives a 403 Forbidden

You have to goto the Admin Panel > Plugins > Roles & Permissions > Permissions > Application > Content then select all and hit Save

Is there a way to do this programmatically?

2 Likes

Responses to the discussion on Github


Mcastres216d ago

Collaborator

Hello @laggingreflex

What you can do is writing this code inside your config/functions/bootstrap.js

"use strict";
/**
 * 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.
 *
 * See more details here: https://strapi.io/documentation/3.0.0-beta.x/concepts/configurations.html#bootstrap
 */
const findPublicRole = async () => {
  const result = await strapi
    .query("role", "users-permissions")
    .findOne({ type: "public" });
  return result;
};

const setDefaultPermissions = async () => {
  const role = await findPublicRole();
  const permissions = await strapi
    .query("permission", "users-permissions")
    .find({ type: "application", role: role.id });
  await Promise.all(
    permissions.map(p =>
      strapi
        .query("permission", "users-permissions")
        .update({ id: p.id }, { enabled: true })
    )
  );
};

const isFirstRun = async () => {
  const pluginStore = strapi.store({
    environment: strapi.config.environment,
    type: "type",
    name: "setup"
  });
  const initHasRun = await pluginStore.get({ key: "initHasRun" });
  await pluginStore.set({ key: "initHasRun", value: true });
  return !initHasRun;
};

module.exports = async () => {
  const shouldSetDefaultPermissions = await isFirstRun();
  if (shouldSetDefaultPermissions) {
    await setDefaultPermissions();
  }
};

It will allow every permissions on all your collection types during the first run of your application.

Thank you!
It would have been great to have something related on the Strapi documentation :slight_smile:
Cheers!

@piwi something we could possibly add to the dev docs, really though, something like this would be for an example after we document the internal API.

1 Like