diff --git a/packages/strapi-plugin-graphql/services/Aggregator.js b/packages/strapi-plugin-graphql/services/Aggregator.js index 206ae3fd78..02a44d179e 100644 --- a/packages/strapi-plugin-graphql/services/Aggregator.js +++ b/packages/strapi-plugin-graphql/services/Aggregator.js @@ -519,14 +519,11 @@ const formatModelConnectionsGQL = function( }); const policiesFn = [ - policyUtils.globalPolicy( - undefined, - { - handler: `${name}.find`, - }, - undefined, - plugin - ), + policyUtils.globalPolicy({ + controller: name, + action: 'find', + plugin, + }), ]; policyUtils.get( diff --git a/packages/strapi-plugin-graphql/services/Mutation.js b/packages/strapi-plugin-graphql/services/Mutation.js index d2cff29993..ba01f3b149 100644 --- a/packages/strapi-plugin-graphql/services/Mutation.js +++ b/packages/strapi-plugin-graphql/services/Mutation.js @@ -73,14 +73,11 @@ module.exports = { // Push global policy to make sure the permissions will work as expected. policiesFn.push( - policyUtils.globalPolicy( - undefined, - { - handler: `${name}.${action}`, - }, - undefined, - plugin - ) + policyUtils.globalPolicy({ + controller: name, + action, + plugin, + }) ); // Return the controller. @@ -109,14 +106,11 @@ module.exports = { // Push global policy to make sure the permissions will work as expected. // We're trying to detect the controller name. policiesFn.push( - policyUtils.globalPolicy( - undefined, - { - handler: `${name}.${action}`, - }, - undefined, - plugin - ) + policyUtils.globalPolicy({ + controller: name, + action, + plugin, + }) ); // Make the query compatible with our controller by @@ -149,14 +143,11 @@ module.exports = { ); } - policiesFn[0] = policyUtils.globalPolicy( - undefined, - { - handler: `${name}.${action}`, - }, - undefined, - plugin - ); + policiesFn[0] = policyUtils.globalPolicy({ + controller: name, + action, + plugin, + }); } if (strapi.plugins['users-permissions']) { diff --git a/packages/strapi-plugin-graphql/services/Query.js b/packages/strapi-plugin-graphql/services/Query.js index 80f1101a58..e052262103 100644 --- a/packages/strapi-plugin-graphql/services/Query.js +++ b/packages/strapi-plugin-graphql/services/Query.js @@ -130,14 +130,11 @@ module.exports = { // Push global policy to make sure the permissions will work as expected. policiesFn.push( - policyUtils.globalPolicy( - undefined, - { - handler: `${name}.${action}`, - }, - undefined, - plugin - ) + policyUtils.globalPolicy({ + controller: name, + action, + plugin, + }) ); // Return the controller. @@ -170,14 +167,11 @@ module.exports = { // Push global policy to make sure the permissions will work as expected. // We're trying to detect the controller name. policiesFn.push( - policyUtils.globalPolicy( - undefined, - { - handler: `${name}.${isSingular ? 'findOne' : 'find'}`, - }, - undefined, - plugin - ) + policyUtils.globalPolicy({ + controller: name, + action: isSingular ? 'findOne' : 'find', + plugin, + }) ); // Make the query compatible with our controller by @@ -221,14 +215,11 @@ module.exports = { ); } - policiesFn[0] = policyUtils.globalPolicy( - undefined, - { - handler: `${name}.${action}`, - }, - undefined, - plugin - ); + policiesFn[0] = policyUtils.globalPolicy({ + controller: name, + action, + plugin, + }); } if (strapi.plugins['users-permissions']) { diff --git a/packages/strapi-utils/lib/cli.js b/packages/strapi-utils/lib/cli.js deleted file mode 100644 index 0c9ef59c8a..0000000000 --- a/packages/strapi-utils/lib/cli.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ - -// Node.js core. -const path = require('path'); - -/** - * Check that we're in a valid Strapi project. - * - * @returns {boolean} - */ - -const isStrapiApp = () => { - const pathToPackageJSON = path.resolve(process.cwd(), 'package.json'); - let validPackageJSON = true; - - try { - require(pathToPackageJSON); - } catch (e) { - validPackageJSON = false; - } - - return validPackageJSON; -}; - -module.exports = { - isStrapiApp -}; diff --git a/packages/strapi-utils/lib/index.js b/packages/strapi-utils/lib/index.js index 14e97e8a2f..238e4ef67a 100644 --- a/packages/strapi-utils/lib/index.js +++ b/packages/strapi-utils/lib/index.js @@ -11,13 +11,10 @@ const sanitizeEntity = require('./sanitize-entity'); const parseType = require('./parse-type'); module.exports = { - cli: require('./cli'), finder: require('./finder'), - knex: require('./knex'), logger: require('./logger'), models: require('./models'), policy: require('./policy'), - regex: require('./regex'), templateConfiguration: require('./templateConfiguration'), convertRestQueryParams, buildQuery, diff --git a/packages/strapi-utils/lib/knex.js b/packages/strapi-utils/lib/knex.js deleted file mode 100644 index 66d4621aa2..0000000000 --- a/packages/strapi-utils/lib/knex.js +++ /dev/null @@ -1,68 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ - -/* eslint-disable prefer-template */ -// Node.js core. -const fs = require('fs'); -const path = require('path'); - -// Public node modules. -const _ = require('lodash'); - -/** - * Check if connection is valid - */ - -module.exports = scope => { - - // First, make sure the application we have access to - // the migration generator. - try { - require.resolve(path.resolve(scope.rootPath, 'node_modules', 'strapi-hook-knex')); - } catch (err) { - console.error('Impossible to call the Knex migration tool.'); - console.error('You can install it with `$ npm install strapi-hook-knex --save`.'); - process.exit(1); - } - - // Try to access the databases config and register connections - // in the Knex query builder. - try { - fs.accessSync(path.resolve(scope.rootPath, 'config', 'environments', scope.environment, 'databases.json'), fs.F_OK | fs.R_OK); - } catch (err) { - console.error('No `databases.json` file detected at `' + path.resolve(scope.rootPath, 'config', 'environments', scope.environment) + '`.'); - console.error(err); - process.exit(1); - } - - // Save the connections and the current DB config. - scope.connections = JSON.parse(fs.readFileSync(path.resolve(scope.rootPath, 'config', 'environments', scope.environment, 'databases.json'))).connections; - scope.dbConfig = _.merge(scope.connections[scope.connection], { - migrations: { - directory: path.resolve(scope.rootPath, 'data', 'migrations', scope.connection) - }, - seeds: { - directory: path.resolve(scope.rootPath, 'data', 'seeds', scope.connection) - } - }); - - // Make sure the specified connection exists in config. - if (!_.has(scope.connections, scope.connection)) { - console.error('No connection found for `' + scope.connection + '`.'); - process.exit(1); - } - - // Make sure the needed client is installed. - _.forEach(scope.connections, config => { - try { - scope.db = require(path.resolve(scope.rootPath, 'node_modules', 'knex'))(scope.dbConfig); - } catch (err) { - console.error('The client `' + config.client + '` is not installed.'); - console.error(err); - process.exit(1); - } - }); -}; diff --git a/packages/strapi-utils/lib/policy.js b/packages/strapi-utils/lib/policy.js index e7496d1265..4d137ea564 100644 --- a/packages/strapi-utils/lib/policy.js +++ b/packages/strapi-utils/lib/policy.js @@ -1,9 +1,8 @@ - // Public dependencies. const _ = require('lodash'); /* eslint-disable prefer-template */ module.exports = { - get: function (policy, plugin, policies = [], endpoint, currentApiName) { + get(policy, plugin, policies = [], endpoint, currentApiName) { // Define global policy prefix. const globalPolicyPrefix = 'global.'; const pluginPolicyPrefix = 'plugins.'; @@ -42,12 +41,14 @@ module.exports = { ) { // Plugin's policies can be used from app APIs with a specific syntax (`plugins.pluginName.policyName`). return policies.push( - this.parsePolicy(_.get( - strapi.plugins, - policySplited[1] + - '.config.policies.' + - policySplited[2].toLowerCase() - )) + this.parsePolicy( + _.get( + strapi.plugins, + policySplited[1] + + '.config.policies.' + + policySplited[2].toLowerCase() + ) + ) ); } else if ( !_.startsWith(policy, globalPolicyPrefix, 0) && @@ -61,10 +62,12 @@ module.exports = { ) { // Plugin policy used in the plugin itself. return policies.push( - this.parsePolicy(_.get( - strapi.plugins, - plugin + '.config.policies.' + policy.toLowerCase() - )) + this.parsePolicy( + _.get( + strapi.plugins, + plugin + '.config.policies.' + policy.toLowerCase() + ) + ) ); } else if ( !_.startsWith(policy, globalPolicyPrefix, 0) && @@ -77,17 +80,21 @@ module.exports = { ) { // API policy used in the API itself. return policies.push( - this.parsePolicy(_.get( - strapi.api, - currentApiName + '.config.policies.' + policy.toLowerCase() - )) + this.parsePolicy( + _.get( + strapi.api, + currentApiName + '.config.policies.' + policy.toLowerCase() + ) + ) ); } - strapi.log.error(`Ignored attempt to bind to ${endpoint} with unknown policy "${policy}"`); + strapi.log.error( + `Ignored attempt to bind to ${endpoint} with unknown policy "${policy}"` + ); }, - parsePolicy: (policy) => { + parsePolicy(policy) { if (_.isFunction(policy)) { return policy; } @@ -97,18 +104,18 @@ module.exports = { // Middleware used for every routes. // Expose the endpoint in `this`. - globalPolicy: (endpoint, value, route = {}, plugin) => { + globalPolicy({ method, endpoint, controller, action, plugin }) { return async (ctx, next) => { ctx.request.route = { - endpoint: _.trim(endpoint), - controller: value.handler.split('.')[0].toLowerCase(), - action: value.handler.split('.')[1].toLowerCase(), - splittedEndpoint: _.trim(route.endpoint), - verb: route.verb && _.trim(route.verb.toLowerCase()), - plugin + endpoint: `${method} ${endpoint}`, + controller, + action, + splittedEndpoint: endpoint, + verb: method, + plugin, }; await next(); }; - } + }, }; diff --git a/packages/strapi-utils/lib/regex.js b/packages/strapi-utils/lib/regex.js deleted file mode 100644 index 171be36978..0000000000 --- a/packages/strapi-utils/lib/regex.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ - -// Public node modules. -const _ = require('lodash'); - -/** - * Detect HTTP verb in an expression. - * - * @api private - */ - -exports.detectRoute = endpoint => { - const verbExpr = /^(all|get|post|put|delete|trace|options|connect|patch|head|redirect)\s+/i; - let verb = _.last(endpoint.match(verbExpr) || []) || ''; - verb = verb.toLowerCase(); - - // If a verb was specified, eliminate the verb from the original string. - if (verb) { - endpoint = endpoint.replace(verbExpr, ''); - } - - // Return the verb and the endpoint. - return { - verb, - endpoint - }; -}; diff --git a/packages/strapi/lib/commands/install.js b/packages/strapi/lib/commands/install.js index 7b10e2d7d3..382cf82ffc 100644 --- a/packages/strapi/lib/commands/install.js +++ b/packages/strapi/lib/commands/install.js @@ -1,18 +1,10 @@ const { join } = require('path'); const { existsSync } = require('fs-extra'); const ora = require('ora'); -const { cyan } = require('chalk'); const execa = require('execa'); -const { cli } = require('strapi-utils'); const findPackagePath = require('../load/package-path'); module.exports = async plugins => { - if (!cli.isStrapiApp()) { - return console.log( - `⛔️ ${cyan('strapi install')} can only be used inside a Strapi project.` - ); - } - const loader = ora(); const dir = process.cwd(); diff --git a/packages/strapi/lib/commands/uninstall.js b/packages/strapi/lib/commands/uninstall.js index 5e86893934..db3ca19ec8 100644 --- a/packages/strapi/lib/commands/uninstall.js +++ b/packages/strapi/lib/commands/uninstall.js @@ -4,18 +4,10 @@ const { join } = require('path'); const { existsSync, rmdirSync } = require('fs-extra'); const ora = require('ora'); const execa = require('execa'); -const { cyan } = require('chalk'); const inquirer = require('inquirer'); -const { cli } = require('strapi-utils'); const findPackagePath = require('../load/package-path'); module.exports = async (plugins, { deleteFiles }) => { - if (!cli.isStrapiApp()) { - return console.log( - `⛔️ ${cyan('strapi install')} can only be used inside a Strapi project.` - ); - } - const answers = await inquirer.prompt([ { type: 'confirm', diff --git a/packages/strapi/lib/middlewares/router/index.js b/packages/strapi/lib/middlewares/router/index.js index be79e763f2..59c7a317a0 100644 --- a/packages/strapi/lib/middlewares/router/index.js +++ b/packages/strapi/lib/middlewares/router/index.js @@ -7,13 +7,13 @@ // Public node modules. const _ = require('lodash'); const Router = require('koa-router'); - +const createEndpointComposer = require('./utils/composeEndpoint'); /** * Router hook */ module.exports = strapi => { - const composeEndpoint = require('./utils/composeEndpoint')(strapi); + const composeEndpoint = createEndpointComposer(strapi); return { /** @@ -22,7 +22,7 @@ module.exports = strapi => { initialize() { _.forEach(strapi.config.routes, value => { - composeEndpoint(value, null, strapi.router); + composeEndpoint(value, { router: strapi.router }); }); strapi.router.prefix( @@ -37,7 +37,7 @@ module.exports = strapi => { }); _.forEach(strapi.admin.config.routes, value => { - composeEndpoint(value, null, router); + composeEndpoint(value, { router }); }); // Mount admin router on Strapi router @@ -46,9 +46,9 @@ module.exports = strapi => { if (strapi.plugins) { // Parse each plugin's routes. - _.forEach(strapi.plugins, (plugin, name) => { + _.forEach(strapi.plugins, (plugin, pluginName) => { const router = new Router({ - prefix: `/${name}`, + prefix: `/${pluginName}`, }); // Exclude routes with prefix. @@ -60,14 +60,17 @@ module.exports = strapi => { _.forEach( _.omit(plugin.config.routes, _.keys(excludedRoutes)), value => { - composeEndpoint(value, name, router); + composeEndpoint(value, { plugin: pluginName, router }); } ); // /!\ Could override main router's routes. if (!_.isEmpty(excludedRoutes)) { _.forEach(excludedRoutes, value => { - composeEndpoint(value, name, strapi.router); + composeEndpoint(value, { + plugin: pluginName, + router: strapi.router, + }); }); } diff --git a/packages/strapi/lib/middlewares/router/utils/composeEndpoint.js b/packages/strapi/lib/middlewares/router/utils/composeEndpoint.js index 19827d4d91..77189786ca 100644 --- a/packages/strapi/lib/middlewares/router/utils/composeEndpoint.js +++ b/packages/strapi/lib/middlewares/router/utils/composeEndpoint.js @@ -2,25 +2,24 @@ const _ = require('lodash'); const compose = require('koa-compose'); +const createRouteChecker = require('./routerChecker'); module.exports = strapi => { - const routerChecker = require('./routerChecker')(strapi); + const routerChecker = createRouteChecker(strapi); - return (value, plugin, router) => { + return (value, { plugin, router }) => { if (_.isEmpty(_.get(value, 'method')) || _.isEmpty(_.get(value, 'path'))) { return; } - const endpoint = `${value.method} ${value.path}`; - - const { policies, action } = routerChecker(value, endpoint, plugin); + const { method, endpoint, policies, action } = routerChecker(value, plugin); if (_.isUndefined(action) || !_.isFunction(action)) { return strapi.log.warn( - `Ignored attempt to bind route '${endpoint}' to unknown controller/action.` + `Ignored attempt to bind route '${value.method} ${value.path}' to unknown controller/action.` ); } - router[value.method.toLowerCase()](value.path, compose(policies), action); + router[method](endpoint, compose(policies), action); }; }; diff --git a/packages/strapi/lib/middlewares/router/utils/routerChecker.js b/packages/strapi/lib/middlewares/router/utils/routerChecker.js index b978d4c37f..7ed5eaf114 100644 --- a/packages/strapi/lib/middlewares/router/utils/routerChecker.js +++ b/packages/strapi/lib/middlewares/router/utils/routerChecker.js @@ -8,11 +8,15 @@ const _ = require('lodash'); // Strapi utilities. -const { finder, regex, policy: policyUtils } = require('strapi-utils'); +const { finder, policy: policyUtils } = require('strapi-utils'); + +const getMethod = route => _.trim(_.toLower(route.method)); +const getEndpoint = route => _.trim(route.path); module.exports = strapi => - function routerChecker(value, endpoint, plugin) { - const route = regex.detectRoute(endpoint); + function routerChecker(value, plugin) { + const method = getMethod(value); + const endpoint = getEndpoint(value); // Define controller and action names. const [controllerName, actionName] = _.trim(value.handler).split('.'); @@ -41,7 +45,15 @@ module.exports = strapi => const policies = []; // Add the `globalPolicy`. - policies.push(policyUtils.globalPolicy(endpoint, value, route, plugin)); + policies.push( + policyUtils.globalPolicy({ + controller, + action: actionName, + method, + endpoint, + plugin, + }) + ); // Allow string instead of array of policies. if ( @@ -56,7 +68,13 @@ module.exports = strapi => !_.isEmpty(_.get(value, 'config.policies')) ) { _.forEach(value.config.policies, policy => { - policyUtils.get(policy, plugin, policies, endpoint, currentApiName); + policyUtils.get( + policy, + plugin, + policies, + `${method} ${endpoint}`, + currentApiName + ); }); } @@ -70,7 +88,8 @@ module.exports = strapi => }); return { - route, + method, + endpoint, policies, action, };