2017-03-02 14:57:33 +03:00
|
|
|
'use strict';
|
|
|
|
|
|
2019-09-16 23:05:59 -04:00
|
|
|
const nconf = require('nconf');
|
|
|
|
|
const winston = require('winston');
|
|
|
|
|
const validator = require('validator');
|
2017-03-02 14:57:33 +03:00
|
|
|
|
2019-09-16 23:05:59 -04:00
|
|
|
const meta = require('../meta');
|
|
|
|
|
const plugins = require('../plugins');
|
2020-06-04 01:14:46 -04:00
|
|
|
const middleware = require('../middleware');
|
2017-03-02 14:57:33 +03:00
|
|
|
|
2018-12-17 16:56:38 -05:00
|
|
|
exports.handle404 = function handle404(req, res) {
|
2019-09-16 23:05:59 -04:00
|
|
|
const relativePath = nconf.get('relative_path');
|
|
|
|
|
const isClientScript = new RegExp('^' + relativePath + '\\/assets\\/src\\/.+\\.js(\\?v=\\w+)?$');
|
2017-03-02 14:57:33 +03:00
|
|
|
|
2020-11-20 16:06:26 -05:00
|
|
|
if (plugins.hooks.hasListeners('action:meta.override404')) {
|
|
|
|
|
return plugins.hooks.fire('action:meta.override404', {
|
2017-03-02 14:57:33 +03:00
|
|
|
req: req,
|
|
|
|
|
res: res,
|
|
|
|
|
error: {},
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (isClientScript.test(req.url)) {
|
2020-08-07 11:30:47 -04:00
|
|
|
res.type('text/javascript').status(404).send('Not Found');
|
2018-10-20 14:40:48 -04:00
|
|
|
} else if (req.path.startsWith(relativePath + '/assets/uploads') || (req.get('accept') && !req.get('accept').includes('text/html')) || req.path === '/favicon.ico') {
|
2017-03-02 14:57:33 +03:00
|
|
|
meta.errors.log404(req.path || '');
|
|
|
|
|
res.sendStatus(404);
|
|
|
|
|
} else if (req.accepts('html')) {
|
|
|
|
|
if (process.env.NODE_ENV === 'development') {
|
|
|
|
|
winston.warn('Route requested but not found: ' + req.url);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
meta.errors.log404(req.path.replace(/^\/api/, '') || '');
|
2017-05-21 19:45:25 -04:00
|
|
|
exports.send404(req, res);
|
2017-03-02 14:57:33 +03:00
|
|
|
} else {
|
|
|
|
|
res.status(404).type('txt').send('Not found');
|
|
|
|
|
}
|
|
|
|
|
};
|
2017-05-21 19:45:25 -04:00
|
|
|
|
2020-06-04 01:14:46 -04:00
|
|
|
exports.send404 = async function (req, res) {
|
2017-05-21 19:45:25 -04:00
|
|
|
res.status(404);
|
2019-09-16 23:05:59 -04:00
|
|
|
const path = String(req.path || '');
|
2017-05-21 19:45:25 -04:00
|
|
|
if (res.locals.isAPI) {
|
|
|
|
|
return res.json({ path: validator.escape(path.replace(/^\/api/, '')), title: '[[global:404.title]]' });
|
|
|
|
|
}
|
2020-06-04 01:14:46 -04:00
|
|
|
await middleware.buildHeaderAsync(req, res);
|
|
|
|
|
res.render('404', { path: validator.escape(path), title: '[[global:404.title]]' });
|
2017-05-21 19:45:25 -04:00
|
|
|
};
|