1. /**
  2. * Normalizes authentication tokens for debugging and error logging.
  3. *
  4. * @param {string} token The authentication token to normalize.
  5. * @returns {object} An object containing the normalized token and any errors encountered.
  6. */
  7. function normalizeToken(token) {
  8. const normalizedToken = {
  9. original: token,
  10. normalized: null,
  11. errors: [],
  12. };
  13. try {
  14. // Basic validation: check if the token is a string.
  15. if (typeof token !== 'string') {
  16. normalizedToken.errors.push("Token must be a string.");
  17. return normalizedToken;
  18. }
  19. //Attempt to decode the token
  20. const decoded = JSON.parse(token);
  21. // Check if the decoded object has expected properties.
  22. if (typeof decoded !== 'object' || decoded === null) {
  23. normalizedToken.errors.push("Invalid token format: Expected a JSON object.");
  24. return normalizedToken;
  25. }
  26. // Add some common debugging properties.
  27. normalizedToken.normalized = {
  28. original: token,
  29. decoded: decoded,
  30. };
  31. } catch (error) {
  32. normalizedToken.errors.push(`Error decoding token: ${error.message}`);
  33. }
  34. return normalizedToken;
  35. }

Add your comment