Move index.html to public middleware + add config var "defaultIndex"

Signed-off-by: Pierre Noël <pierre.noel@strapi.io>
This commit is contained in:
Pierre Noël 2020-03-09 15:48:27 +01:00
parent 2d677be6b4
commit 74e63ea77c
6 changed files with 106 additions and 247 deletions

View File

@ -1,3 +1,6 @@
{
"myCustomConfiguration": "This configuration is accessible through strapi.config.environments.development.myCustomConfiguration"
"myCustomConfiguration": "This configuration is accessible through strapi.config.environments.development.myCustomConfiguration",
"public": {
"defaultIndex": false
}
}

View File

@ -1,56 +0,0 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>Welcome to your Strapi app</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="robots" content="noindex">
<link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Lato:400,700&display=swap" rel="stylesheet" />
<style>
*{-webkit-box-sizing:border-box;text-decoration:none}body,html{margin:0;padding:0;font-size:62.5%;-webkit-font-smoothing:antialiased}body{font-size:1.3rem;font-family:Lato,Helvetica,Arial,Verdana,sans-serif;background:#fafafb;margin:0;padding:80px 0;color:#333740;line-height:1.8rem}strong{font-weight:700}.wrapper{width:684px;margin:auto}h1{text-align:center}h2{font-size:1.8rem;font-weight:700;margin-bottom:1px}.logo{height:40px;margin-bottom:74px}.informations{position:relative;overflow:hidden;display:flex;justify-content:space-between;width:100%;height:126px;margin-top:18px;padding:20px 30px;background:#fff;border-radius:2px;box-shadow:0 2px 4px 0 #e3e9f3}.informations:before{position:absolute;top:0;left:0;content:'';display:block;width:100%;height:2px;background:#007eff}.environment{display:inline-block;padding:0 10px;height:20px;margin-bottom:36px;background:#e6f0fb;border:1px solid #aed4fb;border-radius:2px;text-transform:uppercase;color:#007eff;font-size:1.2rem;font-weight:700;line-height:20px;letter-spacing:.05rem}.cta{display:inline-block;height:30px;padding:0 15px;margin-top:32px;border-radius:2px;color:#fff;font-weight:700;line-height:28px}.cta i{position:relative;display:inline-block;height:100%;vertical-align:middle;font-size:1rem;margin-right:20px}.cta i:before{position:absolute;top:8px}.cta-primary{background:#007eff}.cta-secondary{background:#6dbb1a}.text-align-right{text-align:right}.lets-started{position:relative;overflow:hidden;width:100%;height:144px;margin-top:18px;padding:20px 30px;background:#fff;border-radius:2px;box-shadow:0 2px 4px 0 #e3e9f3}.people-saying-hello{position:absolute;right:30px;bottom:-8px;width:113px;height:70px}.visible{opacity:1!important}.people-saying-hello img{position:absolute;max-width:100%;opacity:0;transition:opacity .2s ease-out}@media only screen and (max-width:768px){.wrapper{width:auto!important;margin:0 20px}.informations{flex-direction:column;height:auto}.environment{width:100%;text-align:center;margin-bottom:18px}.text-align-right{margin-top:18px;text-align:center}.cta{width:100%;text-align:center}.lets-started{height:auto}.people-saying-hello{display:none}}
</style>
</head>
<body lang="en">
<section class="wrapper">
<h1><img class="logo" src="https://strapi.io/assets/images/logo_login.png" /></h1>
<% if (isInitialised) { %>
<div class="informations">
<div>
<span class="environment"><%= strapi.config.environment %></span>
<p>
The server is running successfully (<strong>v<%= strapi.config.info.version %>)</strong>
</p>
</div>
<div class="text-align-right">
<p><%= serverTime %></p>
<a class="cta cta-primary" href="<%= strapi.config.admin.url %>" target="_blank" title="Click to open the administration" ><i class="fas fa-external-link-alt"></i>Open the administration</a>
</div>
</div>
<% } %>
<% if (!isInitialised) { %>
<div class="lets-started">
<h2>Let's get started!</h2>
<p>To discover the power provided by Strapi, you need to create an administrator.</p>
<a class="cta cta-secondary" href="<%= strapi.config.admin.url %>" target="_blank" title="Click to create the first administration" ><i class="fas fa-external-link-alt"></i>Create the first administrator</a>
<div class="people-saying-hello">
<img class="visible" src="https://strapi.io/assets/images/group_people_1.png" alt="People saying hello" />
<img src="https://strapi.io/assets/images/group_people_2.png" alt="People saying hello" />
<img src="https://strapi.io/assets/images/group_people_3.png" alt="People saying hello" />
</div>
</div>
<% } %>
</section>
<script>
var images=document.querySelectorAll('.people-saying-hello img');var nextIndex=0;setInterval(function(){var currentIndex=0;images.forEach(function(image,index){if(image.className==='visible'){currentIndex=index}});nextIndex=currentIndex+1;if(nextIndex===images.length){nextIndex=0}
images.forEach(function(image){image.classList.remove('visible')})
images[nextIndex].classList.add('visible')},1500)
</script>
</body>
</html>

View File

@ -1,30 +0,0 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>Welcome to your Strapi app</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="robots" content="noindex">
<link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Lato:400,700&display=swap" rel="stylesheet" />
<style>
*{-webkit-box-sizing:border-box;text-decoration:none}body,html{margin:0;padding:0;font-size:62.5%;-webkit-font-smoothing:antialiased}body{font-size:1.3rem;font-family:Lato,Helvetica,Arial,Verdana,sans-serif;background:#fafafb;margin:0;padding:80px 0;color:#333740;line-height:1.8rem}strong{font-weight:700}.wrapper{width:684px;margin:auto}h1{text-align:center}h2{font-size:1.8rem;font-weight:700;margin-bottom:1px}.logo{height:40px}.informations{position:relative;overflow:hidden;display:flex;justify-content:space-between;width:100%;height:126px;margin-top:92px;padding:20px 30px;background:#fff;border-radius:2px;box-shadow:0 2px 4px 0 #e3e9f3}.informations:before{position:absolute;top:0;left:0;content:'';display:block;width:100%;height:2px;background:#6dbb1a}.environment{display:inline-block;padding:0 10px;height:20px;margin-bottom:36px;background:#e9f5dd;border:1px solid #6dbb1a;border-radius:2px;text-transform:uppercase;color:#6dbb1a;font-size:1.2rem;font-weight:700;line-height:20px;letter-spacing:.05rem}.cta{display:inline-block;height:30px;padding:0 15px;margin-top:32px;border-radius:2px;color:#fff;font-weight:700;line-height:28px}.cta i{position:relative;display:inline-block;height:100%;vertical-align:middle;font-size:1rem;margin-right:20px}.cta i:before{position:absolute;top:8px}.cta-primary{background:#007eff}.cta-secondary{background:#}.text-align-right{text-align:right}@media only screen and (max-width:768px){.wrapper{width:auto!important;margin:0 20px}.informations{flex-direction:column;height:auto}.informations p{text-align:center}.environment{width:100%;text-align:center;margin-bottom:18px}.text-align-right{margin-top:18px;text-align:center}}
</style>
</head>
<body lang="en">
<section class="wrapper">
<h1><img class="logo" src="https://strapi.io/assets/images/logo_login.png" /></h1>
<div class="informations">
<div>
<span class="environment"><%= strapi.config.environment %></span>
<p>The server is running successfully.</p>
</div>
<div class="text-align-right">
<p><%= serverTime %></p>
</div>
</div>
</section>
</body>
</html>

View File

@ -9,13 +9,7 @@ const getKind = obj => obj.kind || 'collectionType';
const pickSchema = model => {
const schema = _.cloneDeep(
_.pick(model, [
'connection',
'collectionName',
'info',
'options',
'attributes',
])
_.pick(model, ['connection', 'collectionName', 'info', 'options', 'attributes'])
);
schema.kind = getKind(model);
@ -26,32 +20,25 @@ module.exports = function(strapi) {
// Retrieve Strapi version.
strapi.config.uuid = _.get(strapi.config.info, 'strapi.uuid', '');
strapi.config.info.customs = _.get(strapi.config.info, 'strapi', {});
strapi.config.info.strapi = (
_.get(strapi.config, 'info.dependencies.strapi') || ''
).replace(/(\^|~)/g, '');
strapi.config.info.strapi = (_.get(strapi.config, 'info.dependencies.strapi') || '').replace(
/(\^|~)/g,
''
);
strapi.config.info.node = process.versions.node;
// Set connections.
strapi.connections = {};
// Set current environment config.
strapi.config.currentEnvironment =
strapi.config.environments[strapi.config.environment] || {};
strapi.config.currentEnvironment = strapi.config.environments[strapi.config.environment] || {};
const defaultConnection =
strapi.config.currentEnvironment.database.defaultConnection;
const defaultConnection = strapi.config.currentEnvironment.database.defaultConnection;
// Set current connections.
strapi.config.connections = _.get(
strapi.config.currentEnvironment,
'database.connections',
{}
);
strapi.config.connections = _.get(strapi.config.currentEnvironment, 'database.connections', {});
if (_.get(strapi.config, 'language.enabled')) {
strapi.config.language.locales = Object.keys(
_.get(strapi.config, 'locales', {})
);
strapi.config.language.locales = Object.keys(_.get(strapi.config, 'locales', {}));
}
strapi.contentTypes = {};
@ -71,8 +58,7 @@ module.exports = function(strapi) {
apiName,
modelName,
globalId: model.globalId || _.upperFirst(_.camelCase(modelName)),
collectionName:
model.collectionName || `${modelName}`.toLocaleLowerCase(),
collectionName: model.collectionName || `${modelName}`.toLocaleLowerCase(),
connection: model.connection || defaultConnection,
});
@ -133,9 +119,7 @@ module.exports = function(strapi) {
modelName: key,
identity: model.identity || _.upperFirst(key),
globalId: model.globalId || _.upperFirst(_.camelCase(`admin-${key}`)),
connection:
model.connection ||
strapi.config.currentEnvironment.database.defaultConnection,
connection: model.connection || strapi.config.currentEnvironment.database.defaultConnection,
});
strapi.contentTypes[model.uid] = model;
@ -167,13 +151,9 @@ module.exports = function(strapi) {
modelName: key,
uid: `plugins::${pluginName}.${key}`,
plugin: pluginName,
collectionName:
model.collectionName || `${pluginName}_${key}`.toLowerCase(),
globalId:
model.globalId || _.upperFirst(_.camelCase(`${pluginName}-${key}`)),
connection:
model.connection ||
strapi.config.currentEnvironment.database.defaultConnection,
collectionName: model.collectionName || `${pluginName}_${key}`.toLowerCase(),
globalId: model.globalId || _.upperFirst(_.camelCase(`${pluginName}-${key}`)),
connection: model.connection || strapi.config.currentEnvironment.database.defaultConnection,
});
strapi.contentTypes[model.uid] = model;
@ -259,68 +239,54 @@ module.exports = function(strapi) {
}
// Preset config in alphabetical order.
strapi.config.middleware.settings = Object.keys(strapi.middleware).reduce(
(acc, current) => {
// Try to find the settings in the current environment, then in the main configurations.
const currentSettings = _.merge(
_.get(
_.cloneDeep(strapi.middleware[current]),
['defaults', current],
{}
),
flattenMiddlewaresConfig[current] ||
strapi.config.currentEnvironment[current] ||
strapi.config[current]
strapi.config.middleware.settings = Object.keys(strapi.middleware).reduce((acc, current) => {
// Try to find the settings in the current environment, then in the main configurations.
const currentSettings = _.merge(
_.get(_.cloneDeep(strapi.middleware[current]), ['defaults', current], {}),
strapi.config[current],
strapi.config.currentEnvironment[current],
flattenMiddlewaresConfig[current]
);
acc[current] = !_.isObject(currentSettings) ? {} : currentSettings;
if (!_.has(acc[current], 'enabled')) {
strapi.log.warn(
`(middleware:${current}) wasn't loaded due to missing key \`enabled\` in the configuration`
);
acc[current] = !_.isObject(currentSettings) ? {} : currentSettings;
}
if (!_.has(acc[current], 'enabled')) {
strapi.log.warn(
`(middleware:${current}) wasn't loaded due to missing key \`enabled\` in the configuration`
);
}
// Ensure that enabled key exist by forcing to false.
_.defaults(acc[current], { enabled: false });
// Ensure that enabled key exist by forcing to false.
_.defaults(acc[current], { enabled: false });
return acc;
}, {});
return acc;
},
{}
);
strapi.config.hook.settings = Object.keys(strapi.hook).reduce((acc, current) => {
// Try to find the settings in the current environment, then in the main configurations.
const currentSettings = _.merge(
_.get(_.cloneDeep(strapi.hook[current]), ['defaults', current], {}),
flattenHooksConfig[current] ||
_.get(strapi.config.currentEnvironment, ['hook', current]) ||
_.get(strapi.config, ['hook', current])
);
strapi.config.hook.settings = Object.keys(strapi.hook).reduce(
(acc, current) => {
// Try to find the settings in the current environment, then in the main configurations.
const currentSettings = _.merge(
_.get(_.cloneDeep(strapi.hook[current]), ['defaults', current], {}),
flattenHooksConfig[current] ||
_.get(strapi.config.currentEnvironment, ['hook', current]) ||
_.get(strapi.config, ['hook', current])
acc[current] = !_.isObject(currentSettings) ? {} : currentSettings;
if (!_.has(acc[current], 'enabled')) {
strapi.log.warn(
`(hook:${current}) wasn't loaded due to missing key \`enabled\` in the configuration`
);
}
acc[current] = !_.isObject(currentSettings) ? {} : currentSettings;
// Ensure that enabled key exist by forcing to false.
_.defaults(acc[current], { enabled: false });
if (!_.has(acc[current], 'enabled')) {
strapi.log.warn(
`(hook:${current}) wasn't loaded due to missing key \`enabled\` in the configuration`
);
}
// Ensure that enabled key exist by forcing to false.
_.defaults(acc[current], { enabled: false });
return acc;
},
{}
);
return acc;
}, {});
// default settings
strapi.config.port =
_.get(strapi.config.currentEnvironment, 'server.port') ||
strapi.config.port;
strapi.config.host =
_.get(strapi.config.currentEnvironment, 'server.host') ||
strapi.config.host;
strapi.config.port = _.get(strapi.config.currentEnvironment, 'server.port') || strapi.config.port;
strapi.config.host = _.get(strapi.config.currentEnvironment, 'server.host') || strapi.config.host;
// proxy settings
const proxy = _.get(strapi.config.currentEnvironment, 'server.proxy', {});
@ -338,45 +304,24 @@ module.exports = function(strapi) {
port: strapi.config.port,
});
const adminPath = _.get(
strapi.config.currentEnvironment.server,
'admin.path',
'admin'
);
const adminPath = _.get(strapi.config.currentEnvironment.server, 'admin.path', 'admin');
strapi.config.admin.url = new URL(adminPath, strapi.config.url).toString();
};
const enableHookNestedDependencies = function(
strapi,
name,
flattenHooksConfig,
force = false
) {
const enableHookNestedDependencies = function(strapi, name, flattenHooksConfig, force = false) {
// Couldn't find configurations for this hook.
if (_.isEmpty(_.get(flattenHooksConfig, name, true))) {
// Check if database connector is used
const modelsUsed = Object.keys(
_.assign(_.clone(strapi.api) || {}, strapi.plugins)
)
const modelsUsed = Object.keys(_.assign(_.clone(strapi.api) || {}, strapi.plugins))
.filter(x =>
_.isObject(
_.get(strapi.api, [x, 'models']) ||
_.get(strapi.plugins, [x, 'models'])
)
_.isObject(_.get(strapi.api, [x, 'models']) || _.get(strapi.plugins, [x, 'models']))
) // Filter API with models
.map(
x =>
_.get(strapi.api, [x, 'models']) ||
_.get(strapi.plugins, [x, 'models'])
) // Keep models
.map(x => _.get(strapi.api, [x, 'models']) || _.get(strapi.plugins, [x, 'models'])) // Keep models
.filter(models => {
const apiModelsUsed = Object.keys(models).filter(model => {
const connector = _.get(
strapi.config.connections,
models[model].connection,
{}
).connector;
const connector = _.get(strapi.config.connections, models[model].connection, {})
.connector;
if (connector) {
return connector.replace('strapi-hook-', '') === name;

View File

@ -17,6 +17,10 @@ const utils = require('../../utils');
* Public assets hook
*/
const defaults = {
defaultIndex: true,
};
module.exports = strapi => {
return {
/**
@ -24,58 +28,19 @@ module.exports = strapi => {
*/
async initialize() {
const { maxAge } = strapi.config.middleware.settings.public;
const { defaultIndex, maxAge } = Object.assign(
{},
defaults,
strapi.config.middleware.settings.public
);
const staticDir = path.resolve(
strapi.dir,
strapi.config.middleware.settings.public.path || strapi.config.paths.static
);
const indexFileName = 'index.html';
const indexPath = path.join(staticDir, indexFileName);
if (fs.existsSync(indexPath)) {
const index = fs.readFileSync(indexPath, 'utf8');
const renderer = _.template(index); // Is the project initialized?
const renderIndexPage = async () => {
const isInitialised = await utils.isInitialised(strapi);
const data = {
serverTime: new Date().toUTCString(),
isInitialised,
..._.pick(strapi, [
'config.info.version',
'config.info.name',
'config.admin.url',
'config.environment',
]),
};
return renderer(data);
};
const serveIndexPage = async ctx => {
ctx.url = indexFileName;
const content = await renderIndexPage();
const body = stream.Readable({
read() {
this.push(Buffer.from(content));
this.push(null);
},
});
// Serve static.
ctx.type = 'html';
ctx.body = body;
};
// Serve /public index page.
strapi.router.get('/', serveIndexPage);
strapi.router.get(`/${indexFileName}`, serveIndexPage);
}
// Match every route with an extension.
// The file without extension will not be served.
// Note: This route could be override by the user.
// Note: This route can be overriden by the user.
strapi.router.get(
'/*',
async (ctx, next) => {
@ -90,6 +55,38 @@ module.exports = strapi => {
})
);
if (defaultIndex) {
const index = fs.readFileSync(path.join(__dirname, 'index.html'), 'utf8');
const serveIndexPage = async ctx => {
ctx.url = 'index.html';
const isInitialised = await utils.isInitialised(strapi);
const data = {
serverTime: new Date().toUTCString(),
isInitialised,
..._.pick(strapi, [
'config.info.version',
'config.info.name',
'config.admin.url',
'config.environment',
]),
};
const content = _.template(index)(data);
const body = stream.Readable({
read() {
this.push(Buffer.from(content));
this.push(null);
},
});
// Serve static.
ctx.type = 'html';
ctx.body = body;
};
strapi.router.get('/', serveIndexPage);
strapi.router.get('/index.html', serveIndexPage);
}
if (!strapi.config.serveAdminPanel) return;
const basename = _.get(strapi.config.currentEnvironment.server, 'admin.path')
@ -106,7 +103,7 @@ module.exports = strapi => {
await next();
},
koaStatic(buildDir, {
index: indexFileName,
index: '/',
maxage: maxAge,
defer: false,
})