/**
* Normalizes authentication tokens for debugging and error logging.
*
* @param {string} token The authentication token to normalize.
* @returns {object} An object containing the normalized token and any errors encountered.
*/
function normalizeToken(token) {
const normalizedToken = {
original: token,
normalized: null,
errors: [],
};
try {
// Basic validation: check if the token is a string.
if (typeof token !== 'string') {
normalizedToken.errors.push("Token must be a string.");
return normalizedToken;
}
//Attempt to decode the token
const decoded = JSON.parse(token);
// Check if the decoded object has expected properties.
if (typeof decoded !== 'object' || decoded === null) {
normalizedToken.errors.push("Invalid token format: Expected a JSON object.");
return normalizedToken;
}
// Add some common debugging properties.
normalizedToken.normalized = {
original: token,
decoded: decoded,
};
} catch (error) {
normalizedToken.errors.push(`Error decoding token: ${error.message}`);
}
return normalizedToken;
}
Add your comment