zcatalyst-cli
Version:
Command Line Tool for CATALYST
86 lines (85 loc) • 2.97 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const https_1 = __importDefault(require("https"));
const querystring_1 = __importDefault(require("querystring"));
exports.default = (req, res, next) => {
const app = req.app;
const bestRule = res.locals.bestRule;
const types = bestRule.authentication;
if (types === undefined || types === null) {
if (req.url.startsWith('/baas/logout')) {
app.locals.auth = {};
}
next();
return;
}
if (app.locals.auth === undefined) {
app.locals.auth = {};
}
if (app.locals.auth[req.url] === undefined) {
app.locals.auth[req.url] = {};
}
const currentTypeByValue = types.reduce((accumulator, type) => {
switch (type) {
case 'APIKey':
const apikey = req.query.ZCFKEY === undefined ? req.get('ZCFKEY') : req.query.ZCFKEY;
if (apikey !== undefined) {
accumulator[0] = type;
accumulator[1] = apikey + '';
req.headers.ZCFKEY = apikey + '';
}
break;
case 'OAuth':
const oauthHeader = req.get('authorization');
if (oauthHeader !== undefined) {
accumulator[0] = type;
accumulator[1] = oauthHeader;
}
break;
case 'CatalystUserManagement':
const csrfToken = req.cookies.ZD_CSRF_TOKEN;
if (csrfToken !== undefined) {
accumulator[0] = type;
accumulator[1] = csrfToken;
}
break;
}
return accumulator;
}, []);
if (currentTypeByValue.length === 0) {
next(new Error('NO_ACCESS'));
return;
}
if (app.locals.auth[req.url][currentTypeByValue[1]]) {
next();
return;
}
const data = querystring_1.default.stringify({
type: currentTypeByValue[0]
});
const projectId = req.headers['x-zc-projectid'];
const headers = ['cookie', 'authorization', 'ZCFKEY'].reduce((result, headerName) => {
if (req.headers[headerName] !== undefined) {
result[headerName] = req.headers[headerName];
}
return result;
}, {});
const authReq = https_1.default.get(`https://${req.headers['x-zc-project-domain']}/baas/${projectId}/check-auth?${data}`, {
headers
}, (serverRes) => {
if (serverRes.statusCode === 200) {
app.locals.auth[req.url][currentTypeByValue[1]] = true;
next();
}
else {
next(new Error('NO_ACCESS'));
}
});
authReq.on('error', () => {
next(new Error('NO_ACCESS'));
});
authReq.end();
};