Skip to content

Commit

Permalink
switches to fetch in couch-request.js
Browse files Browse the repository at this point in the history
Signed-off-by: Diana Barsan <[email protected]>
  • Loading branch information
dianabarsan committed Jan 14, 2025
1 parent b3cee4a commit c10ac9d
Show file tree
Hide file tree
Showing 14 changed files with 162 additions and 127 deletions.
24 changes: 12 additions & 12 deletions api/src/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ module.exports = {
getUserCtx: req => {
return get('/_session', req.headers)
.catch(err => {
if (err.statusCode === 401) {
if (err.status === 401) {
throw { code: 401, message: 'Not logged in', err: err };
}
throw err;
Expand Down Expand Up @@ -83,12 +83,12 @@ module.exports = {
* @return {Object} {username: username, password: password}
*/
basicAuthCredentials: req => {
const authHeader = req && req.headers && req.headers.authorization;
const authHeader = req?.headers?.authorization;
if (!authHeader || !authHeader.startsWith('Basic ')) {
return false;
}
try {
const [username, password] = Buffer.from(authHeader.split(' ')[1], 'base64').toString().split(':');
const [username, password] = atob(authHeader.split(' ')[1]).split(':');
return { username, password };
} catch (err) {
throw Error('Corrupted Auth header');
Expand All @@ -101,16 +101,16 @@ module.exports = {
* @param {Object} Credentials object as created by basicAuthCredentials
*/
validateBasicAuth: ({ username, password }) => {
const authUrl = new URL(environment.serverUrlNoAuth);
authUrl.username = username;
authUrl.password = password;
return request.head({
uri: authUrl.toString(),
resolveWithFullResponse: true
})
return request
.get({
uri: environment.serverUrlNoAuth,
auth: { username, password },
simple: false,
json: false,
})
.then(res => {
if (res.statusCode !== 200) {
return Promise.reject(new Error(`Expected 200 got ${res.statusCode}`));
if (!res.ok) {
return Promise.reject(new Error(`Expected 200 got ${res.status}`));
}
return username;
});
Expand Down
15 changes: 6 additions & 9 deletions api/src/controllers/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -160,22 +160,19 @@ const render = (page, req, extras = {}) => {
};

const getSessionCookie = res => {
return _.find(
res.headers['set-cookie'],
cookie => cookie.indexOf('AuthSession') === 0
);
return res.headers.getSetCookie().find(cookie => cookie.indexOf('AuthSession') === 0);
};

const createSession = req => {
const user = req.body.user;
const password = req.body.password;

return request.post({
url: new URL('/_session', environment.serverUrlNoAuth).toString(),
json: true,
resolveWithFullResponse: true,
simple: false, // doesn't throw an error on non-200 responses
body: { name: user, password: password },
auth: { user: user, pass: password },
auth: { username: user, password: password },
});
};

Expand Down Expand Up @@ -242,7 +239,7 @@ const getUserCtxRetry = async (options, retry = 10) => {

const createSessionRetry = (req, retry=10) => {
return createSession(req).then(sessionRes => {
if (sessionRes.statusCode === 200) {
if (sessionRes.status === 200) {
return sessionRes;
}

Expand Down Expand Up @@ -303,8 +300,8 @@ const renderLogin = (req) => {
const login = async (req, res) => {
try {
const sessionRes = await createSession(req);
if (sessionRes.statusCode !== 200) {
res.status(sessionRes.statusCode).json({ error: 'Not logged in' });
if (sessionRes.status !== 200) {
res.status(sessionRes.status).json({ error: 'Not logged in' });
} else {
const redirectUrl = await setCookies(req, res, sessionRes);
res.status(302).send(redirectUrl);
Expand Down
11 changes: 6 additions & 5 deletions api/src/db-batch.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,12 @@ const runBatch = (ddoc, view, viewParams, iteratee) => {
});
// using request here instead of PouchDB because
// PouchDB doesn't support startkey_docid: #5319
return request.get({
url: fullUrl,
json: true,
auth: { user: environment.username, pass: environment.password },
})
return request
.get({
url: fullUrl,
json: true,
auth: { username: environment.username, password: environment.password },
})
.then(result => {
logger.info(` Processing doc ${result.offset}`);
let nextPage;
Expand Down
2 changes: 1 addition & 1 deletion api/src/migrations/fix-user-db-security.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ module.exports = {
return p.then(() => {
return userDb.setSecurity(userDb.getDbName(username), username)
.catch(err => {
if (err.statusCode !== 404) {
if (err.status !== 404) {
throw err;
}
// db not found is ok
Expand Down
4 changes: 2 additions & 2 deletions api/src/migrations/restrict-access-to-audit-db.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ const addMemberToDb = () => {
pathname: `${environment.db}-audit/_security`,
}),
auth: {
user: environment.username,
pass: environment.password
username: environment.username,
password: environment.password
},
json: true,
body: securityObject
Expand Down
4 changes: 2 additions & 2 deletions api/src/migrations/restrict-access-to-sentinel-db.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ const addSecurityToDb = () => {
pathname: `${environment.db}-sentinel/_security`,
}),
auth: {
user: environment.username,
pass: environment.password
username: environment.username,
password: environment.password
},
json: true,
body: securityObject
Expand Down
4 changes: 2 additions & 2 deletions api/src/migrations/restrict-access-to-vault-db.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ const addSecurityToDb = () => {
pathname: `${environment.db}-vault/_security`,
}),
auth: {
user: environment.username,
pass: environment.password
username: environment.username,
password: environment.password
},
json: true,
body: securityObject
Expand Down
30 changes: 15 additions & 15 deletions api/src/services/africas-talking.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const getRecipient = res => {
res.SMSMessageData.Recipients[0];
};

const getStatus = recipient => recipient && STATUS_MAP[recipient.statusCode];
const getStatus = recipient => recipient && STATUS_MAP[recipient.status];

const generateStateChange = (message, res) => {
const recipient = getRecipient(res);
Expand Down Expand Up @@ -85,20 +85,20 @@ const parseResponseBody = body => {
const sendMessage = (credentials, message) => {
const url = getUrl(credentials.username === 'sandbox');
logger.debug(`Sending message to "${url}"`);
return request.post({
url: url,
simple: false,
form: {
username: credentials.username,
from: credentials.from,
to: message.to,
message: message.content
},
headers: {
apikey: credentials.apiKey,
Accept: 'application/json'
}
})
return request
.post({
url: url,
form: {
username: credentials.username,
from: credentials.from,
to: message.to,
message: message.content
},
headers: {
apikey: credentials.apiKey,
Accept: 'application/json'
}
})
.then(body => {
const result = parseResponseBody(body);
if (!result) {
Expand Down
4 changes: 2 additions & 2 deletions api/src/services/rapidpro.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ const sendMessage = (credentials, message) => {
})
.catch(err => {
logger.error(`Error thrown when trying to send message: %o`, err);
if (err?.statusCode === 400) {
if (err?.status === 400) {
// source https://rapidpro.io/api/v2/
// 400: The request failed due to invalid parameters.
// Do not retry with the same values, and the body of the response will contain details.
Expand Down Expand Up @@ -168,7 +168,7 @@ const getRemoteStates = (credentials, messages) => {
stateUpdates.push(stateUpdate);
})
.catch(err => {
if (err && err.statusCode === 429) {
if (err && err.status === 429) {
// rate limited, throw error to halt recursive polling
throttled = true;
}
Expand Down
4 changes: 2 additions & 2 deletions api/src/services/user-db.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ module.exports = {
pathname: `${dbName}/_security`,
}),
auth: {
user: environment.username,
pass: environment.password
username: environment.username,
password: environment.password
},
json: true,
body: {
Expand Down
Loading

0 comments on commit c10ac9d

Please sign in to comment.