token.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. const STORAGE_KEY = 'token';
  2. const VALID_SPAN = 30 * 24 * 3600 * 1000; // 有效期,默认30天
  3. let app = '';
  4. /**
  5. * 判断本地存储的 token 是否有效
  6. */
  7. export function isTokenValided(expiresIn) {
  8. return Date.now() <= expiresIn;
  9. }
  10. /**
  11. * 保存 Token 到本地,默认保存有效期 30 天
  12. * @param {String} options.token
  13. * @param {String} options.phone
  14. * @returns {Promise}
  15. */
  16. export function setTokenStorage(options) {
  17. return new Promise((resolve, reject) => {
  18. const data = {
  19. expiresIn: Date.now() + VALID_SPAN,
  20. userInfo: {
  21. token: options.userInfo.token,
  22. phone: options.userInfo.phone,
  23. userID: options.userInfo.userID,
  24. userSig: options.userInfo.userSig,
  25. },
  26. };
  27. if (!app) {
  28. app = getApp();
  29. }
  30. app.globalData.expiresIn = data.expiresIn;
  31. wx.setStorage({
  32. key: STORAGE_KEY,
  33. data,
  34. success: resolve,
  35. fail: reject,
  36. });
  37. });
  38. }
  39. export function getTokenStorage() {
  40. return new Promise((resolve, reject) => {
  41. wx.getStorage({
  42. key: STORAGE_KEY,
  43. success: ({
  44. data,
  45. }) => {
  46. resolve(data);
  47. },
  48. fail: reject,
  49. });
  50. });
  51. }
  52. export function removeTokenStorage() {
  53. return new Promise((resolve, reject) => {
  54. wx.removeStorage({
  55. key: STORAGE_KEY,
  56. success: resolve,
  57. fail: reject,
  58. });
  59. });
  60. }