Skip to content

Commit

Permalink
Merge pull request #897 from PiusKariuki/support-PAT-for-DHIS2
Browse files Browse the repository at this point in the history
Support PAT for dhis2
  • Loading branch information
josephjclark authored Jan 14, 2025
2 parents 2da52d7 + c19d561 commit 1bee83e
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 11 deletions.
5 changes: 5 additions & 0 deletions .changeset/giant-lobsters-vanish.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@openfn/language-dhis2': major
---

Added support for personal access tokens in dhis2
9 changes: 9 additions & 0 deletions packages/dhis2/configuration-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,15 @@
"examples": [
"v2"
]
},
"pat": {
"title": "Personal Access Token",
"type": "string",
"description": "Personal access token",
"minLength": 1,
"examples": [
"d2pat_vreYExmi0yh92Soy8CCF2zHG0wRjID494035128247"
]
}
},
"type": "object",
Expand Down
35 changes: 24 additions & 11 deletions packages/dhis2/src/Client.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ import Qs from 'qs';
* before spreading the rest of the axios configuration, and (3) executes an
* axios request.
* @function
* @param {object} configuration - configuration must have a username and password
* @param {object} configuration - configuration can either be a username and password OR a personal access token
* @param {object} axiosRequest - the axiosRequest contains valid axios params: https://axios-http.com/docs/req_config
* @returns {Promise} a promise that will resolve to either a response object or an error object.
*/
export function request({ username, password }, axiosRequest) {
export function request({ username, password, pat }, axiosRequest) {
const { method, url, params } = axiosRequest;

console.log(`Sending ${method} request to ${url}`);
Expand All @@ -22,13 +22,26 @@ export function request({ username, password }, axiosRequest) {
method.toLowerCase()
);

return axios({
headers: { 'Content-Type': 'application/json' },
responseType: 'json',
maxRedirects: safeRedirect ? 5 : 0,
auth: { username, password },
paramsSerializer: params => Qs.stringify(params, { arrayFormat: 'repeat' }),
// Note that providing headers or auth in the request object will overwrite.
...axiosRequest,
});
// Declare auth property and headers dynamically
const headers = { 'Content-Type': 'application/json'}
let auth;

if(pat){
headers.Authorization = `ApiToken ${pat}`
} else {
auth = { username, password }
}


return axios(
{
headers,
responseType: 'json',
auth,
maxRedirects: safeRedirect ? 5 : 0,
paramsSerializer: params => Qs.stringify(params, { arrayFormat: 'repeat' }),
// Note that providing headers or auth in the request object will overwrite.
...axiosRequest,
}
);
}

0 comments on commit 1bee83e

Please sign in to comment.