Skip to content

Commit

Permalink
fix: db authentication options
Browse files Browse the repository at this point in the history
  • Loading branch information
paulpascal committed May 18, 2024
1 parent 79c5850 commit 2ecd475
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 49 deletions.
65 changes: 32 additions & 33 deletions src/lib/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ const archivingApi = require('./archiving-api');
const environment = require('./environment');
const log = require('./log');
const url = require('url');
const nools = require('./nools-utils');

const cache = new Map();

Expand All @@ -18,9 +17,9 @@ const withCookieSession = (...args) => {
Object.assign(options, ...args.slice(1));
}

const sessionTokenHeader = nools.sessionTokenHeader(environment);
if (sessionTokenHeader || options.headers) {
options.headers = Object.assign({}, options.headers || {}, sessionTokenHeader);
const sessionToken = environment.sessionToken;
if (sessionToken || options.headers) {
options.headers = Object.assign({}, options.headers || {}, { Cookie: sessionToken });
}

return options;
Expand Down Expand Up @@ -66,7 +65,7 @@ const logDeprecatedTransitions = (settings) => {
const updateAppSettings = (settings) => {
return request.put({
url: `${environment.apiUrl}/_design/medic/_rewrite/update_settings/medic?replace=1`,
headers: { 'Content-Type': 'application/json' },
headers: {'Content-Type': 'application/json'},
body: settings,
});
};
Expand All @@ -76,9 +75,9 @@ const api = {
const url = `${environment.apiUrl}/_design/medic/_rewrite/app_settings/medic`;
return request.get({ url, json: true })
.catch(err => {
if (err.statusCode === 404) {
if(err.statusCode === 404) {
throw new Error(`Failed to fetch existing app_settings from ${url}.\n` +
` Check that CHT API is running and that you're connecting on the correct port!`);
` Check that CHT API is running and that you're connecting on the correct port!`);
} else {
throw err;
}
Expand Down Expand Up @@ -175,38 +174,38 @@ const api = {
if (!this._formsValidateEndpointFound) {
// The endpoint to validate forms doesn't exist in the API,
// (old version), so we assume form is valid but return special result
return Promise.resolve({ ok: true, formsValidateEndpointFound: false });
return Promise.resolve({ok: true, formsValidateEndpointFound: false});
}
return request.post({
uri: `${environment.instanceUrl}/api/v1/forms/validate`,
headers: { 'Content-Type': 'application/xml' },
body: formXml,
})
.then(resp => {
try {
return JSON.parse(resp);
} catch (e) {
throw new Error('Invalid JSON response validating XForm against the API: ' + resp);
}
})
.catch(err => {
if (err.statusCode === 404) {
// The endpoint doesn't exist in the API (old CHT version), so
// we assume the form is valid but return special JSON
// highlighting the situation, and remembering the lack
// of the endpoint so next call there is no need
// to call the missed endpoint again
this._formsValidateEndpointFound = false;
return { ok: true, formsValidateEndpointFound: false };
}
if (err.statusCode === 400 && err.error) {
throw new Error(JSON.parse(err.error).error);
}
throw err;
});
.then(resp => {
try {
return JSON.parse(resp);
} catch (e) {
throw new Error('Invalid JSON response validating XForm against the API: ' + resp);
}
})
.catch(err => {
if (err.statusCode === 404) {
// The endpoint doesn't exist in the API (old CHT version), so
// we assume the form is valid but return special JSON
// highlighting the situation, and remembering the lack
// of the endpoint so next call there is no need
// to call the missed endpoint again
this._formsValidateEndpointFound = false;
return {ok: true, formsValidateEndpointFound: false};
}
if (err.statusCode === 400 && err.error) {
throw new Error(JSON.parse(err.error).error);
}
throw err;
});
},

async getCompressibleTypes() {
async getCompressibleTypes () {
const parsedUrl = new url.URL(environment.apiUrl);
const baseUrl = `${parsedUrl.protocol}//${parsedUrl.username}:${parsedUrl.password}@${parsedUrl.host}`;
const configUrl = `${baseUrl}/api/couch-config-attachments`;
Expand All @@ -215,7 +214,7 @@ const api = {
return cache.get('compressibleTypes');
}
const resp = await request.get({ url: configUrl, json: true });
const compressibleTypes = resp.compressible_types.split(',').map(s => s.trim());
const compressibleTypes = resp.compressible_types.split(',').map(s=>s.trim());
cache.set('compressibleTypes', compressibleTypes);
return compressibleTypes;
} catch (e) {
Expand All @@ -231,7 +230,7 @@ const api = {

Object.entries(api)
.filter(([key, value]) => typeof value === 'function' && !archivingApi[key])
.forEach(([key,]) => {
.forEach(([key, ]) => {
archivingApi[key] = () => {
// if this error is raised, somebody forgot to add a mock
// implementation to ./archiving-api.js or the action isn't
Expand Down
15 changes: 12 additions & 3 deletions src/lib/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,22 @@ PouchDB.plugin(require('pouchdb-mapreduce'));

const ArchivingDB = require('./archiving-db');
const environment = require('./environment');
const nools = require('./nools-utils');

module.exports = () => {
if (environment.isArchiveMode) {
return new ArchivingDB(environment.archiveDestination);
}
const headers = nools.sessionTokenHeader(environment);
return new PouchDB(environment.apiUrl, { ajax: { timeout: 60000, headers } });

return new PouchDB(environment.apiUrl, {
ajax: { timeout: 60000 },
fetch: (url, opts) => {
const sessionToken = environment.sessionToken;
if (sessionToken) {
opts.headers.set('Cookie', sessionToken);
opts.credentials = 'include';
}
return PouchDB.fetch(url, opts);
},
});
};

6 changes: 3 additions & 3 deletions src/lib/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ module.exports = async (argv, env) => {
const expectedOptions = ['alpha', projectName];
if (productionUrlMatch && !expectedOptions.includes(productionUrlMatch[1])) {
warn(`Attempting to use project for \x1b[31m${projectName}\x1b[33m`,
`against non-matching instance: \x1b[31m${redactBasicAuth(environment.instanceUrl)}\x1b[33m`);
`against non-matching instance: \x1b[31m${redactBasicAuth(environment.instanceUrl)}\x1b[33m`);
if (!userPrompt.keyInYN()) {
throw new Error('User aborted execution.');
}
Expand All @@ -182,7 +182,7 @@ module.exports = async (argv, env) => {
// GO GO GO
//
info(`Processing config in ${projectName}.`);
info('Actions:\n -', actions.map(({ name }) => name).join('\n - '));
info('Actions:\n -', actions.map(({name}) => name).join('\n - '));

const skipCheckForUpdates = cmdArgs.check === false;
if (actions.some(action => action.name === 'check-for-updates') && !skipCheckForUpdates) {
Expand Down Expand Up @@ -216,7 +216,7 @@ function buildActions(cmdArgs, skipValidate) {
actions = actions.filter(a => a !== 'check-git');
}

if (skipValidate) {
if(skipValidate) {
warn('Skipping all form validation.');
const validateActions = [
'validate-app-forms',
Expand Down
15 changes: 5 additions & 10 deletions src/lib/nools-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ const minify = js =>
js.split('\n')
.map(s =>
s.trim()
.replace(/\s*\/\/.*/, '') // single-line comments (like this one)
.replace(/\s*\/\/.*/, '') // single-line comments (like this one)
).join('')
.replace(/\s*\/\*(?:(?!\*\/).)*\*\/\s*/g, '') /* this kind of comment */
.replace(/function \(/g, 'function(') // different node versions do function.toString() differently :\
;
.replace(/\s*\/\*(?:(?!\*\/).)*\*\/\s*/g, '') /* this kind of comment */
.replace(/function \(/g, 'function(') // different node versions do function.toString() differently :\
;

const addBoilerplateToCode = code => `define Target { _id: null, contact: null, deleted: null, type: null, pass: null, date: null, groupBy: null }
define Contact { contact: null, reports: null, tasks: null }
Expand All @@ -15,12 +15,7 @@ rule GenerateEvents {
when { c: Contact } then { ${code} }
}`;

const sessionTokenHeader = environment => {
return environment.sessionToken ? { Cookie: `${environment.sessionToken}` } : undefined;
};

module.exports = {
addBoilerplateToCode,
minify,
sessionTokenHeader,
};
};

0 comments on commit 2ecd475

Please sign in to comment.