uniapp,h5

index.js 1.8KB

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