Skip to content

Instantly share code, notes, and snippets.

@chuckreynolds
Last active August 8, 2024 18:08
Show Gist options
  • Save chuckreynolds/bddeb76fe371caeb3deaeba1d1f08c84 to your computer and use it in GitHub Desktop.
Save chuckreynolds/bddeb76fe371caeb3deaeba1d1f08c84 to your computer and use it in GitHub Desktop.
This script manages the authentication process and token refresh mechanism for Wikimedia Enterprise API requests in Postman. It checks the validity of the access and refresh tokens before each request, performing re-authentication or token refresh as needed. The script uses environment variables to store tokens and their generation times, ensuri…
/**
* This script manages the authentication process and token refresh mechanism for Wikimedia Enterprise API requests in Postman.
* It checks the validity of the access and refresh tokens before each request, performing re-authentication or token refresh
* as needed. The script uses environment variables to store tokens and their generation times, ensuring the tokens are
* up-to-date and minimizing the need for repeated login requests.
*
* ## Author/Support
* - @chuckreynolds on X
* - e: [email protected]
*
* ## Details:
* - Timestamp Handling: The script uses `getCurrentTimestamp()` to get the current time in milliseconds and `daysDifference()` to calculate the difference in days between the current time and a given timestamp.
* - Token Checks: It checks if the tokens and their generation times exist in the environment. If not, it performs authentication by calling the `authenticate()` function.
* - Token Expiry Handling:
* - If `refresh_token_generated_time` is more than 90 days old, it re-authenticates by calling the `authenticate()` function.
* - If `access_token_generated_time` is more than 24 hours old, it refreshes the access token by calling the `refreshAccessToken()` function.
* - If the tokens are still valid, it proceeds with the request.
* - API Calls: The script uses `pm.sendRequest()` to perform API calls to either authenticate or refresh the access token.
* - Error Handling: It logs errors to the console if authentication or token refresh fails, providing feedback for debugging.
*
* ## Usage:
* - Add this script to the “Pre-request Script” tab at the collection level in Postman
* - Ensure your environment variables filled in correctly:
* - auth_server (default) == `https://auth.enterprise.wikimedia.com`
* - wmeUsername (default)
* - wmePassword (secret)
* - Ensure you have blank environment variables:
* - access_token (secret)
* - refresh_token (secret)
* - access_token_generated_time (default)
* - refresh_token_generated_time (default)
*/
// Helper function to get the current timestamp
function getCurrentTimestamp() {
return new Date().getTime();
}
// Helper function to calculate the difference in days
function daysDifference(timestamp) {
const msInDay = 1000 * 60 * 60 * 24;
const currentTime = getCurrentTimestamp();
return (currentTime - timestamp) / msInDay;
}
// Environment variables
const accessToken = pm.environment.get("access_token");
const refreshToken = pm.environment.get("refresh_token");
const accessTokenGeneratedTime = pm.environment.get("access_token_generated_time");
const refreshTokenGeneratedTime = pm.environment.get("refresh_token_generated_time");
// Check if tokens and times exist
if (!accessToken || !refreshToken || !accessTokenGeneratedTime || !refreshTokenGeneratedTime) {
// No tokens or timestamps, perform login
authenticate();
} else {
const refreshTokenAge = daysDifference(parseInt(refreshTokenGeneratedTime, 10));
if (refreshTokenAge > 90) {
// Refresh token is older than 90 days, perform login
authenticate();
} else {
const accessTokenAge = daysDifference(parseInt(accessTokenGeneratedTime, 10));
// Validate that accessTokenAge is a number
if (!isNaN(accessTokenAge) && accessTokenAge > 1) {
// Access token is older than 24 hours, refresh the access token
refreshAccessToken();
} else {
// Access token is valid, continue with the request
console.log("Access token is still valid. Proceeding with the request.");
}
}
}
// Function to authenticate and get new tokens
function authenticate() {
console.log("Performing authentication...");
pm.sendRequest({
url: pm.environment.get("auth_server") + "/v1/login",
method: "POST",
header: {
"Content-Type": "application/json"
},
body: {
mode: 'raw',
raw: JSON.stringify({
username: pm.environment.get("wmeUsername"),
password: pm.environment.get("wmePassword")
})
}
}, function (err, response) {
if (!err && response.code === 200) {
const jsonData = response.json();
pm.environment.set("access_token", jsonData.access_token);
pm.environment.set("refresh_token", jsonData.refresh_token);
const currentTime = getCurrentTimestamp();
pm.environment.set("access_token_generated_time", currentTime);
pm.environment.set("refresh_token_generated_time", currentTime);
console.log("Authentication successful. Tokens updated.");
} else {
console.error("Authentication failed: ", err || response.status);
}
});
}
// Function to refresh the access token
function refreshAccessToken() {
console.log("Refreshing access token...");
pm.sendRequest({
url: pm.environment.get("auth_server") + "/v1/token-refresh",
method: "POST",
header: {
"Content-Type": "application/json"
},
body: {
mode: 'raw',
raw: JSON.stringify({
username: pm.environment.get("wmeUsername"),
refresh_token: pm.environment.get("refresh_token")
})
}
}, function (err, response) {
if (!err && response.code === 200) {
const jsonData = response.json();
pm.environment.set("access_token", jsonData.access_token);
pm.environment.set("access_token_generated_time", getCurrentTimestamp());
console.log("Access token refreshed successfully.");
} else {
console.error("Failed to refresh access token: ", err || response.status);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment