all repos — caroster @ e9c732f6628feb42d5ba39eabc8c48a4bb716530

[Octree] Group carpool to your event https://caroster.io

backend/config/functions/bootstrap.js (view raw)

 1'use strict';
 2const {NODE_ENV} = process.env;
 3const permissions = require('../permissions.json');
 4
 5/**
 6 * An asynchronous bootstrap function that runs before
 7 * your application gets started.
 8 *
 9 * This gives you an opportunity to set up your data model,
10 * run jobs, or perform some special logic.
11 *
12 * See more details here: https://strapi.io/documentation/v3.x/concepts/configurations.html#bootstrap
13 */
14
15module.exports = async () => {
16  /**
17   * Set permissions
18   */
19
20  // For each role, set permissions
21  const roles = Object.keys(permissions.roles);
22  await Promise.all(
23    roles.map(async roleType => {
24      // Get role entity in Strapi db
25      const role = await strapi.query('role', 'users-permissions').findOne({
26        type: roleType,
27      });
28      // If role doesn't exist, skip
29      if (!role) return [];
30
31      // Enable or create permissions for each roles, controllers and actions
32      const perms = permissions.roles[roleType];
33      return perms.map(({type, controllers}) =>
34        controllers.map(({name: controller, actions}) =>
35          actions.map(async action => {
36            const existingPerm = await strapi
37              .query('permission', 'users-permissions')
38              .findOne({
39                role: role.id,
40                type,
41                controller,
42                action,
43              });
44            if (existingPerm) {
45              if (existingPerm.enabled) return false; // If permission already enabled, skip
46              if (NODE_ENV !== 'test')
47                strapi.log.debug(
48                  `Enable permission ${type}.${controller}.${action} for role ${roleType}.`
49                );
50
51              return strapi
52                .query('permission', 'users-permissions')
53                .update(
54                  {role: role.id, type, controller, action},
55                  {enabled: true}
56                );
57            } else {
58              strapi.log.info(
59                `Create permission ${type}.${controller}.${action} for role ${roleType}.`
60              );
61              return strapi.query('permission', 'users-permissions').create({
62                role: role.id,
63                type,
64                controller,
65                action,
66                enabled: true,
67              });
68            }
69          })
70        )
71      );
72    })
73  );
74};