uniapp,h5

index.js 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. export class InvalidTokenError extends Error {
  2. }
  3. InvalidTokenError.prototype.name = "InvalidTokenError";
  4. function b64DecodeUnicode(str) {
  5. return decodeURIComponent(atob(str).replace(/(.)/g, (m, p) => {
  6. let code = p.charCodeAt(0).toString(16).toUpperCase();
  7. if (code.length < 2) {
  8. code = "0" + code;
  9. }
  10. return "%" + code;
  11. }));
  12. }
  13. function base64UrlDecode(str) {
  14. let output = str.replace(/-/g, "+").replace(/_/g, "/");
  15. switch (output.length % 4) {
  16. case 0:
  17. break;
  18. case 2:
  19. output += "==";
  20. break;
  21. case 3:
  22. output += "=";
  23. break;
  24. default:
  25. throw new Error("base64 string is not of the correct length");
  26. }
  27. try {
  28. return b64DecodeUnicode(output);
  29. }
  30. catch (err) {
  31. return atob(output);
  32. }
  33. }
  34. export function jwtDecode(token, options) {
  35. if (typeof token !== "string") {
  36. throw new InvalidTokenError("Invalid token specified: must be a string");
  37. }
  38. options || (options = {});
  39. const pos = options.header === true ? 0 : 1;
  40. const part = token.split(".")[pos];
  41. if (typeof part !== "string") {
  42. throw new InvalidTokenError(`Invalid token specified: missing part #${pos + 1}`);
  43. }
  44. let decoded;
  45. try {
  46. decoded = base64UrlDecode(part);
  47. }
  48. catch (e) {
  49. throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${pos + 1} (${e.message})`);
  50. }
  51. try {
  52. return JSON.parse(decoded);
  53. }
  54. catch (e) {
  55. throw new InvalidTokenError(`Invalid token specified: invalid json for part #${pos + 1} (${e.message})`);
  56. }
  57. }