@fontoxml/fontoxml-development-tools
Version:
Development tools for Fonto.
57 lines (49 loc) • 1.5 kB
JavaScript
import fs from 'fs-extra';
import auth from 'http-auth';
import path from 'path';
import correlationIdRepository from '../connectors-cms-standard/correlationIdRepository.js';
import asyncRouteWithLockCleanupHandler from '../asyncRouteWithLockCleanupHandler.js';
/** @typedef {import('../../src/getAppConfig.js').DevCmsConfig} DevCmsConfig */
/**
* Basic authentication middleware.
*
* @param {DevCmsConfig} config
*/
export default (config) => {
const passwordFilePath = path.join(config.root, 'users.htpasswd');
if (config.distAuth && !fs.existsSync(passwordFilePath)) {
throw new Error(
'There should be a password file called "users.htpasswd" when running the editor in dist mode with basic authentication enabled.',
);
}
const basicAuth = auth.basic({
realm: 'Fonto Access Restricted',
file: passwordFilePath,
});
return asyncRouteWithLockCleanupHandler(
async (_acquireLock, req, res, next) => {
// Determine if we can check auth based on a correlation id.
if (!correlationIdRepository.canValidateRequest(req)) {
basicAuth.check((_req, _res, error) => (error ? next(error) : next()))(
req,
res,
);
return;
}
// Fonto correlation id auth
try {
const passed = await correlationIdRepository.validateRequest(req);
if (!passed) {
basicAuth.check((_req, _res, error) =>
error ? next(error) : next(),
)(req, res);
return;
}
} catch (error) {
next(error);
return;
}
next();
},
);
};