Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: setup configuration in one place only #19273

Merged
merged 1 commit into from Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 2 additions & 3 deletions packages/core/admin/ee/server/src/services/auth.ts
@@ -1,5 +1,4 @@
import _ from 'lodash';
import { getAbsoluteAdminUrl } from '@strapi/utils';
import { errors } from '@strapi/utils';
import { getService } from '../utils';
import { isSsoLocked } from '../utils/sso-lock';
Expand All @@ -23,8 +22,8 @@ const forgotPassword = async ({ email }: any = {}) => {
await getService('user').updateById(user.id, { resetPasswordToken });

// Send an email to the admin.
const url = `${getAbsoluteAdminUrl(
strapi.config
const url = `${strapi.config.get(
'admin.absoluteUrl'
)}/auth/reset-password?code=${resetPasswordToken}`;
return strapi
.plugin('email')
Expand Down
2 changes: 1 addition & 1 deletion packages/core/admin/server/src/register.ts
Expand Up @@ -10,7 +10,7 @@ export default ({ strapi }: { strapi: Strapi }) => {
strapi.get('auth').register('admin', adminAuthStrategy);
strapi.get('auth').register('content-api', apiTokenAuthStrategy);

if (strapi.config.serveAdminPanel) {
if (strapi.config.get('admin.serveAdminPanel')) {
registerAdminPanelRoute({ strapi });
}
};
6 changes: 3 additions & 3 deletions packages/core/admin/server/src/services/auth.ts
@@ -1,6 +1,6 @@
import bcrypt from 'bcryptjs';
import _ from 'lodash';
import { getAbsoluteAdminUrl, errors } from '@strapi/utils';
import { errors } from '@strapi/utils';
import { getService } from '../utils';
import type { AdminUser } from '../../../shared/contracts/shared';
import '@strapi/types';
Expand Down Expand Up @@ -63,8 +63,8 @@ const forgotPassword = async ({ email } = {} as { email: string }) => {
await getService('user').updateById(user.id, { resetPasswordToken });

// Send an email to the admin.
const url = `${getAbsoluteAdminUrl(
strapi.config
const url = `${strapi.config.get(
'admin.absoluteUrl'
)}/auth/reset-password?code=${resetPasswordToken}`;

return strapi
Expand Down
2 changes: 1 addition & 1 deletion packages/core/admin/server/src/services/token.ts
Expand Up @@ -67,7 +67,7 @@ const decodeJwtToken = (
};

const checkSecretIsDefined = () => {
if (strapi.config.serveAdminPanel && !strapi.config.get('admin.auth.secret')) {
if (strapi.config.get('admin.serveAdminPanel') && !strapi.config.get('admin.auth.secret')) {
throw new Error(
`Missing auth.secret. Please set auth.secret in config/admin.js (ex: you can generate one using Node with \`crypto.randomBytes(16).toString('base64')\`).
For security reasons, prefer storing the secret in an environment variable and read it in config/admin.js. See https://docs.strapi.io/developer-docs/latest/setup-deployment-guides/configurations/optional/environment.html#configuration-using-environment-variables.`
Expand Down
3 changes: 0 additions & 3 deletions packages/core/core/src/Strapi.ts
Expand Up @@ -59,7 +59,6 @@ import createStartupLogger from './utils/startup-logger';
import { createStrapiFetch } from './utils/fetch';
import { LIFECYCLES } from './utils/lifecycles';
import ee from './utils/ee';
import bootstrap from './bootstrap';
import { destroyOnSignal } from './utils/signals';
import getNumberOfDynamicZones from './services/utils/dynamic-zones';
import convertCustomFieldType from './utils/convert-custom-field-type';
Expand Down Expand Up @@ -470,8 +469,6 @@ class Strapi extends Container implements StrapiI {
async register() {
await loaders.loadApplicationContext(this);

await bootstrap({ strapi: this });

// init webhook runner
this.webhookRunner = createWebhookRunner({
eventHub: this.eventHub,
Expand Down
32 changes: 0 additions & 32 deletions packages/core/core/src/bootstrap.ts

This file was deleted.

18 changes: 16 additions & 2 deletions packages/core/core/src/configuration/index.ts
Expand Up @@ -5,6 +5,8 @@ import _ from 'lodash';
import { omit } from 'lodash/fp';
import dotenv from 'dotenv';
import type { Config } from '@strapi/types';
import { getConfigUrls, getAbsoluteAdminUrl, getAbsoluteServerUrl } from '@strapi/utils';

import loadConfigDir from './config-loader';

dotenv.config({ path: process.env.ENV_PATH });
Expand Down Expand Up @@ -53,7 +55,6 @@ export default (dirs: { app: string; dist: string }, initialConfig: any = {}) =>

const rootConfig = {
launchedAt: Date.now(),
serveAdminPanel,
autoReload,
environment: process.env.NODE_ENV,
uuid: _.get(pkgJSON, 'strapi.uuid'),
Expand All @@ -62,12 +63,25 @@ export default (dirs: { app: string; dist: string }, initialConfig: any = {}) =>
...pkgJSON,
strapi: strapiVersion,
},
admin: {
serveAdminPanel,
},
};

const baseConfig = omit('plugins', loadConfigDir(configDir)); // plugin config will be loaded later

const envDir = path.resolve(configDir, 'env', process.env.NODE_ENV as string);
const envConfig = loadConfigDir(envDir);

return _.merge(rootConfig, defaultConfig, baseConfig, envConfig);
const config = _.merge(rootConfig, defaultConfig, baseConfig, envConfig);

const { serverUrl, adminUrl, adminPath } = getConfigUrls(config);

_.set(config, 'server.url', serverUrl);
_.set(config, 'server.absoluteUrl', getAbsoluteServerUrl(config));
_.set(config, 'admin.url', adminUrl);
_.set(config, 'admin.path', adminPath);
_.set(config, 'admin.absoluteUrl', getAbsoluteAdminUrl(config));

return config;
};
3 changes: 1 addition & 2 deletions packages/core/core/src/utils/open-browser.ts
@@ -1,10 +1,9 @@
import open from 'open';
import { getAbsoluteAdminUrl } from '@strapi/utils';

import type { ConfigProvider } from '@strapi/types';

async function openBrowser(config: ConfigProvider) {
const url = getAbsoluteAdminUrl(config);
const url = config.get<string>('admin.absoluteUrl');

return open(url);
}
Expand Down
9 changes: 4 additions & 5 deletions packages/core/core/src/utils/startup-logger.ts
@@ -1,7 +1,6 @@
import chalk from 'chalk';
import CLITable from 'cli-table3';
import _ from 'lodash/fp';
import { getAbsoluteAdminUrl, getAbsoluteServerUrl } from '@strapi/utils';

import type { Strapi } from '@strapi/types';

Expand Down Expand Up @@ -49,7 +48,7 @@ export default (app: Strapi) => {

const addressTable = new CLITable();

const adminUrl = getAbsoluteAdminUrl(strapi.config);
const adminUrl = strapi.config.get('admin.absoluteUrl');
alexandrebodin marked this conversation as resolved.
Show resolved Hide resolved
addressTable.push([chalk.bold(adminUrl)]);

console.log(`${addressTable.toString()}`);
Expand All @@ -64,15 +63,15 @@ export default (app: Strapi) => {

console.log(chalk.bold('Welcome back!'));

if (app.config.serveAdminPanel === true) {
if (app.config.get('admin.serveAdminPanel') === true) {
console.log(chalk.grey('To manage your project 🚀, go to the administration panel at:'));
const adminUrl = getAbsoluteAdminUrl(strapi.config);
const adminUrl = strapi.config.get('admin.absoluteUrl');
console.log(chalk.bold(adminUrl));
console.log();
}

console.log(chalk.grey('To access the server ⚡️, go to:'));
const serverUrl = getAbsoluteServerUrl(strapi.config);
const serverUrl = strapi.config.get('server.absoluteUrl');
console.log(chalk.bold(serverUrl));
console.log();
},
Expand Down
15 changes: 9 additions & 6 deletions packages/core/utils/src/config.ts
Expand Up @@ -4,18 +4,21 @@ import type { Config } from './types';

interface ServerConfig {
url: string;
host: string;
port: number | string;
}

export const getConfigUrls = (config: Config, forAdminBuild = false) => {
const serverConfig = config.get<ServerConfig>('server');
const adminConfig = config.get('admin');
const serverConfig = config.server as ServerConfig;
const adminConfig = config.admin;

// Defines serverUrl value
let serverUrl = _.get(serverConfig, 'url', '');
serverUrl = _.trim(serverUrl, '/ ');
if (typeof serverUrl !== 'string') {
throw new Error('Invalid server url config. Make sure the url is a string.');
}

if (serverUrl.startsWith('http')) {
try {
serverUrl = _.trim(new URL(serverConfig.url).toString(), '/');
Expand Down Expand Up @@ -75,13 +78,13 @@ const getAbsoluteUrl =
return url;
}

const serverConfig = config.server as ServerConfig;
const hostname =
config.get('environment') === 'development' &&
['127.0.0.1', '0.0.0.0'].includes(config.get('server.host'))
config.environment === 'development' && ['127.0.0.1', '0.0.0.0'].includes(serverConfig.host)
? 'localhost'
: config.get('server.host');
: serverConfig.host;

return `http://${hostname}:${config.get('server.port')}${url}`;
return `http://${hostname}:${serverConfig.port}${url}`;
};

export const getAbsoluteAdminUrl = getAbsoluteUrl('admin');
alexandrebodin marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
4 changes: 1 addition & 3 deletions packages/core/utils/src/types.ts
Expand Up @@ -8,9 +8,7 @@ export type Data = {
[key: string]: string | number | ID | boolean | null | undefined | Date | Data | Data[];
};

export interface Config {
get<T = unknown>(key: string, defaultVal?: T): T;
}
export interface Config extends Record<string, unknown> {}

export interface Attribute {
type: string;
Expand Down
Expand Up @@ -3,7 +3,6 @@
const path = require('path');
const fs = require('fs-extra');
const { produce } = require('immer');
const { getAbsoluteServerUrl } = require('@strapi/utils');
const { builApiEndpointPath, buildComponentSchema } = require('./helpers');

const defaultOpenApiComponents = require('./utils/default-openapi-components');
Expand Down Expand Up @@ -150,7 +149,7 @@ module.exports = ({ strapi }) => {
(draft) => {
if (draft.servers.length === 0) {
// When no servers found set the defaults
const serverUrl = getAbsoluteServerUrl(strapi.config);
const serverUrl = strapi.config.get('server.absoluteUrl');
const apiPath = strapi.config.get('api.rest.prefix');
draft.servers = [
{
Expand Down
6 changes: 3 additions & 3 deletions packages/plugins/users-permissions/server/controllers/auth.js
Expand Up @@ -22,7 +22,7 @@ const {
validateChangePasswordBody,
} = require('./validation/auth');

const { getAbsoluteAdminUrl, getAbsoluteServerUrl, sanitize } = utils;
const { sanitize } = utils;
const { ApplicationError, ValidationError, ForbiddenError } = utils.errors;

const sanitizeUser = (user, ctx) => {
Expand Down Expand Up @@ -234,8 +234,8 @@ module.exports = {
resetPasswordSettings.message,
{
URL: advancedSettings.email_reset_password,
SERVER_URL: getAbsoluteServerUrl(strapi.config),
ADMIN_URL: getAbsoluteAdminUrl(strapi.config),
SERVER_URL: strapi.config.get('server.absoluteUrl'),
ADMIN_URL: strapi.config.get('admin.absoluteUrl'),
USER: userInfo,
TOKEN: resetPasswordToken,
}
Expand Down
Expand Up @@ -8,7 +8,6 @@
const _ = require('lodash');
const urlJoin = require('url-join');

const { getAbsoluteServerUrl } = require('@strapi/utils');
const { getService } = require('../utils');

module.exports = ({ strapi }) => {
Expand Down Expand Up @@ -105,7 +104,13 @@ module.exports = ({ strapi }) => {

const buildRedirectUri = (provider = '') => {
const apiPrefix = strapi.config.get('api.rest.prefix');
return urlJoin(getAbsoluteServerUrl(strapi.config), apiPrefix, 'connect', provider, 'callback');
return urlJoin(
strapi.config.get('server.absoluteUrl'),
apiPrefix,
'connect',
provider,
'callback'
);
};

return {
Expand Down
12 changes: 8 additions & 4 deletions packages/plugins/users-permissions/server/services/user.js
Expand Up @@ -10,7 +10,7 @@ const crypto = require('crypto');
const bcrypt = require('bcryptjs');
const urlJoin = require('url-join');

const { getAbsoluteAdminUrl, getAbsoluteServerUrl, sanitize } = require('@strapi/utils');
const { sanitize } = require('@strapi/utils');
const { getService } = require('../utils');

module.exports = ({ strapi }) => ({
Expand Down Expand Up @@ -112,9 +112,13 @@ module.exports = ({ strapi }) => ({

try {
settings.message = await userPermissionService.template(settings.message, {
URL: urlJoin(getAbsoluteServerUrl(strapi.config), apiPrefix, '/auth/email-confirmation'),
SERVER_URL: getAbsoluteServerUrl(strapi.config),
ADMIN_URL: getAbsoluteAdminUrl(strapi.config),
URL: urlJoin(
strapi.config.get('server.absoluteUrl'),
apiPrefix,
'/auth/email-confirmation'
),
SERVER_URL: strapi.config.get('server.absoluteUrl'),
ADMIN_URL: strapi.config.get('admin.absoluteUrl'),
USER: sanitizedUserInfo,
CODE: confirmationToken,
});
Expand Down