Authentication process
This guide will help you manage the authentication process and token refresh
Last updated
// Import the necessary modules - axios and form-data may need to be installed, or you can use your own HTTP client
import axios from 'axios';
import FormData from 'form-data';
import jwt from 'jsonwebtoken';
// Initialize your API key, client secret, and initial token
const apiKey = 'YOUR-API-KEY';
const clientSecret = 'CLIENT-SECRET';
const apiRoot = 'https://api.waldo.ai';
let currentToken = null;
// Function to refresh your token
const refreshToken = async () => {
try{
// Make a request to the API to refresh your token
const data = JSON.stringify({
apiKey: apiKey,
clientSecret: clientSecret
});
const response = await axios.request({
method: 'post',
url: `${apiRoot}/authenticate`,
headers: {
'Content-Type': 'application/json'
},
data: data
});
// Update the current token
currentToken = response.data.token;
}catch(error){
console.log(error);
}
};
const testToken = async () => {
try {
// Verify the token with the secret key
const decodedToken = jwt.verify(currentToken, clientSecret);
// Check the 'exp' claim in the decoded token
const { exp } = decodedToken;
// Get the current timestamp in seconds
const currentTimestamp = Math.floor(Date.now() / 1000);
// Compare the expiration timestamp with the current timestamp
return exp && exp > currentTimestamp;
} catch (error) {
// Token is invalid or has expired
return false;
}
};
// Function to make an authenticated API request
const makeAuthenticatedRequest = async () => {
try {
// Check if we have a valid token or obtain a new one
if (!await testToken()) {
await refreshToken();
}
const response = await axios.request({
method: 'GET',
url: `${apiRoot}/some-endpoint`,
headers: {
'Authorization': `Bearer ${currentToken}`,
'Content-Type': 'application/json',
},
});
if (response) {
// Handle the successful response here
const responseData = response.data;
} else if (response.status === 401) {
// Token expired, obtain a new one and update currentToken
await refreshToken();
return makeAuthenticatedRequest(); // Retry the original request
} else {
throw new Error('API request failed');
}
// Check if there is a new token in the response headers
const newToken = response.headers.get('Authorization');
if (newToken) {
currentToken = newToken; // Update currentToken
}
} catch (error) {
throw 'Error making an API request: ' + error.message;
}
};
await makeAuthenticatedRequest();